Frantisek
Frantisek

Reputation: 7693

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?

Upvotes: 22

Views: 55192

Answers (1)

Sarfraz
Sarfraz

Reputation: 382696

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.

Upvotes: 39

Related Questions