Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace special characters with regex in javascript?

I need to replace special characters from a string, like this:

this.value = this.value.replace(/\n/g,'');

Except for the regex part, I need it to look for the opposite of all these:

[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z

plus underscore and minus.

Therefore, this string is OK:

Abc054_34-bd

And this string is bad:

Fš 04//4.

From the bad string I need the disallowed characters removed.

How do I stack this regex rule?

like image 440
Frantisek Avatar asked Feb 16 '12 12:02

Frantisek


People also ask

How do you replace special characters in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you handle special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you change special characters in node JS?

To replace special characters, use replace() in JavaScript.


2 Answers

You can use character class with ^ negation:

this.value = this.value.replace(/[^a-zA-Z0-9_-]/g,'');

Tests:

console.log('Abc054_34-bd'.replace(/[^a-zA-Z0-9_-]/g,'')); // Abc054_34-bd
console.log('Fš 04//4.'.replace(/[^a-zA-Z0-9_-]/g,'')); // F044

So by putting characters in [^...], you can decide which characters should be allowed and all others replaced.

like image 101
Sarfraz Avatar answered Sep 25 '22 15:09

Sarfraz


Try:

this.value = this.value.replace(/\w|-/g, '');

Reference:

  • Regular Expressions, at the Mozilla Developer Network.
like image 30
David Thomas Avatar answered Sep 25 '22 15:09

David Thomas