1

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 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, I assumed ^ would only be for matching starting with. I forgot the dual usage! Thanks for your help.
@thefourtheye possibly clear \W instead of [^a-zA-Z]
@Grundy \W will not remove the number 1 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.