I want to replace all characters in a string apart from English alpabets. My current regex is of the nature, 'ab-aml1'.replace(/![a-zA-Z]/g,''). I would expect this to return abaml. However it returns the entire string passed to it. How can I do a negation selection?
1 Answer
JavaScript's logical NOT operator will not work in RegEx. If you want any other data apart from alphabets to be removed, you can use [^a-zA-Z]. It is called negated character set and it means that, anything which is NOT a-zA-Z.
console.log('ab-aml1'.replace(/[^a-zA-Z]/g,''));
Output
abaml
3 Comments
Amal Antony
Oh, I assumed
^ would only be for matching starting with. I forgot the dual usage! Thanks for your help.Grundy
@thefourtheye possibly clear
\W instead of [^a-zA-Z]thefourtheye
@Grundy
\W will not remove the number 1 :)