Removing non-alphanumeric chars(删除非字母数字字符)
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
(以下是从输入字符串中删除非字母数字字符的正确正则表达式:)
input.replace(/W/g, '')
Note that \W
is the equivalent of [^0-9a-zA-Z_]
- it includes the underscore character.
(注意\W
相当于[^0-9a-zA-Z_]
- 它包含下划线字符。)
To also remove underscores use eg:(要删除下划线,请使用例如:)
input.replace(/[^0-9a-z]/gi, '')
The input is malformed(输入格式错误)
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
(由于测试字符串包含各种不是字母数字的转义字符,因此它将删除它们。)
A backslash in the string needs escaping if it's to be taken literally:
(字符串中的反斜杠如果需要字面意思,则需要转义:)
"\test\red\bob\fred\new".replace(/W/g, '')
"testredbobfrednew" // output
Handling malformed strings(处理格式错误的字符串)
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
(如果你无法正确地转义输入字符串(为什么不能?),或者它来自某种不受信任/配置错误的源 - 你可以这样做:)
JSON.stringify("\test
edobfred
ew").replace(/W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
(请注意,字符串的json表示包括引号:)
JSON.stringify("\test
edobfred
ew")
""\test
edobfred
ew""
But they are also removed by the replacement regex.
(但它们也被替代正则表达式删除。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…