简体   繁体   English

从文本中删除特殊字符

[英]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将是:

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. [^\\dA-Za-z]否定的字符类,它匹配任何字符,但不匹配数字或字母。

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/g作为正则表达式

\\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/ http://jsfiddle.net/vgwv6ht2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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