Why does
var a = "1ab";
a = a.replace(/[^\d][a-z]/g, "");
remove “a” and “b”? I thought that it should remove only “b” because “a” is preceeded by a number which I excluded by [^\d].
Who can help me?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It removes them because your character class
[^\d]means “anything that is not a digit.” The^means “not” and\dmeans “digit”. So your expression means “match anything that is not a digit followed by any lowercase letter”, which matches"ab".To remove only lowercase letters that don’t have a digit in front of them, it’s probably easiest to do it with a capture group:
That says: Match a digit followed by a lowercase letter (as a group) followed by a lowercase letter (outside the group), and replace it with just the group’s contents. If you want to remove
"c"from"1abc", add a+after the last[a-z], e.g.:/([\d][a-z])[a-z]+/g.