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?
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]+", "")
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).
To replace special characters, use replace() in JavaScript.
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.
Try:
this.value = this.value.replace(/\w|-/g, '');
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With