javascript 正则表达式 - 从与表达式不匹配的字符串中删除所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11802385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex - Remove everything from a string that does not match an expression
提问by MindWire
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-]/, "");
回答by newfurniturey
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 notin the brackets (i.e. - the characters you want to strip).
The g
modifier performs a global-match on the entire input string.
该^
字符作为方括号内的第一个字符[]
,指定匹配不在方括号中的内容(即 - 要删除的字符)。
该g
修改执行对整个输入字符串一个全球性的匹配。
回答by burning_LEGION
var result = userInput.replace(/[^\w-]/g, '');
var result = userInput.replace(/[^\w-]/g, '');
回答by André Silva
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_]