remove special characters from text

305 Views Asked by At

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!

4

There are 4 best solutions below

1
On BEST ANSWER

Just use.

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

Output

"ab cd abc 123 AAA"

0
On

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'
0
On

You have bad regex there, it should be:

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

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/