正则表达式 - 从与表达式不匹配的字符串中删除所有内容

时间:2022-07-15 16:51:52

I am creating a JavaScript function that will take a user inputted value and and create a CSS class name out of it. The following expression can be used to detect whether the end result follows valid css rules

我正在创建一个JavaScript函数,它将获取用户输入的值,并从中创建一个CSS类名。以下表达式可用于检测最终结果是否遵循有效的css规则

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

but I need to find a way to use it to remove all invalid characters.

但我需要找到一种方法来使用它来删除所有无效字符。

I was thinking of something like:

我想的是:

var newClass = userInput.replace(EVERYTHING BUT /[_a-zA-Z0-9-]/, "");

3 个解决方案

#1


14  

A very small modification to your existing regex should work, using the ^ operator and g:

使用^运算符和g对现有正则表达式进行非常小的修改应该有效:

/[^a-zA-Z0-9_-]+/g

Which should be used as:

哪个应该用作:

var newClass = userInput.replace(/[^a-zA-Z0-9-_]/g, '');

The ^ character, as the first character inside the brackets [], specifies to match what's not in the brackets (i.e. - the characters you want to strip).
The g modifier performs a global-match on the entire input string.

^字符,作为方括号[]内的第一个字符,指定匹配括号中没有的字符(即 - 要删除的字符)。 g修饰符对整个输入字符串执行全局匹配。

#2


2  

var result = userInput.replace(/[^\w-]/g, '');

var result = userInput.replace(/ [^ \ w - ] / g,'');

#3


1  

var newClass = userInput.replace(/\W/, "");

\w equals to [a-zA-Z0-9_]

\ w等于[a-zA-Z0-9_]

\W equals to [^a-zA-Z0-9_]

\ W等于[^ a-zA-Z0-9_]

#1


14  

A very small modification to your existing regex should work, using the ^ operator and g:

使用^运算符和g对现有正则表达式进行非常小的修改应该有效:

/[^a-zA-Z0-9_-]+/g

Which should be used as:

哪个应该用作:

var newClass = userInput.replace(/[^a-zA-Z0-9-_]/g, '');

The ^ character, as the first character inside the brackets [], specifies to match what's not in the brackets (i.e. - the characters you want to strip).
The g modifier performs a global-match on the entire input string.

^字符,作为方括号[]内的第一个字符,指定匹配括号中没有的字符(即 - 要删除的字符)。 g修饰符对整个输入字符串执行全局匹配。

#2


2  

var result = userInput.replace(/[^\w-]/g, '');

var result = userInput.replace(/ [^ \ w - ] / g,'');

#3


1  

var newClass = userInput.replace(/\W/, "");

\w equals to [a-zA-Z0-9_]

\ w等于[a-zA-Z0-9_]

\W equals to [^a-zA-Z0-9_]

\ W等于[^ a-zA-Z0-9_]