简体   繁体   中英

remove special characters from text

I am trying to remove special characters from a given text.

I've tried to replace it with:

var stringToReplace = 'ab風cd  👰� abc 123 € AAA';
var newText = stringToReplace.replace(/[^\d.-]/g, '');

but it's not working. I want that the newText will be:

newText = 'ab cd      abc 123   AAA'

I've tried some regex but none of them seem to work. the real problem is with '風' (those kind of characters). any suggestion? Thanks!

Just use.

stringToReplace.replace(/\W/g, ' ');

Output

"ab cd abc 123 AAA"

You could try the below,

> 'ab風cd  👰� abc 123 € AAA'.replace(/[^\dA-Za-z]/g, " ")
'ab cd      abc 123   AAA'

[^\\dA-Za-z] negated character class which matches any character but not of digits or alphabets.

OR

> 'ab風cd  👰� abc 123 € AAA'.replace(/[^\dA-Za-z\s]/g, "")
'abcd   abc 123  AAA'
> 'ab風cd  👰� abc 123 € AAA'.replace(/[^\dA-Za-z\s]/g, " ")
'ab cd      abc 123   AAA'

您的正则表达式不好,应该是:

var newText = stringToReplace.replace(/[^\da-z]/ig, ' ');

You could use /\\W/g as your regex

\\W - The opposite of \\w. Matches any non-alphanumeric character.

For example:

var string = 'ab風cd  👰� abc 123 € AAA';
string = string.replace(/\W/g, ' ')
alert(string); // ab cd      abc 123   AAA

http://jsfiddle.net/vgwv6ht2/

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