1

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!

Bakbuk
  • 31
  • 2

4 Answers4

2

Just use.

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

Output

"ab cd abc 123 AAA"

void
  • 36,090
  • 8
  • 62
  • 107
  • thanks, it works! but what if I want Hebrew letters to stay in the text, for example: 'ab風cd � abc 123 € AAA שלום' expected text: 'ab cd abc 123 AAA שלום' – Bakbuk Feb 22 '15 at 07:18
0

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'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You have bad regex there, it should be:

var newText = stringToReplace.replace(/[^\da-z]/ig, ' ');
pavel
  • 26,538
  • 10
  • 45
  • 61
0

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/

SubjectCurio
  • 4,702
  • 3
  • 32
  • 46