简体   繁体   中英

How can I keep the spacing in this Javascript regex?

/[^A-Za-z0-9]/g

Right now it trims off the space. But I want to keep the space. (I just want to remove the symbols)

This

[A-Za-z0-9]

is a character class . It will match any character that is listed inside that class.

If you put a ^ as starting character inside the class

[^A-Za-z0-9]

it is a negated character class . It will match any character that is NOT listed inside that class.

So if you don't want the space to be matched, just add it to the class:

[^A-Za-z0-9 ]

If you want to keep all whitespace (spaces, tabs, and line breaks) you can use the shorthand character class \\s

[^A-Za-z0-9\s]

JavaScript Code:

var s = '#fashion!?;Foobar,.;:'; 
s = s.replace(/[^A-Za-z0-9 ]/g, ''); 
alert(s);

puts

fashionFoobar

My Blog post: What absolutely every Programmer should know about regular expressions

只需添加空格字符。

/[^A-Za-z0-9 ]/g

您可以尝试以下方法:

/[^\sA-Za-z0-9]/g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM