Vibhav Singh Rohilla
Vibhav Singh Rohilla

Reputation: 768

JavaScript regex not replacing '@' character

I am new to JavaScipt and testing a regular Expression and is working on below use case -

Requirement - Replace every character with '#' that is NOT FROM BELOW LIST-

Please find my code below -

    var replacedStr = str.replace(/[^a-zA-Z0-9'.-\[\], ]/g,"#");

Output for various values of str are -

   str = "hello_";
   replacedStr is hello#
   _______________________
   str = "hello@_";
   replacedStr is hello@#

I wanted to know why '@' isnot being replaced from above regex.

The same behavior is with characters - underScore, question-Mark, Angular brackets.

Please guide.

Thanks,

Vibhav

Upvotes: 0

Views: 82

Answers (3)

selvakumar
selvakumar

Reputation: 654

Hyphen will be taken as a range, hence you need to add a escape sequence to it.

str.replace(/[^a-zA-Z0-9'.\-\[\]]/g,"#");

Upvotes: 0

Manish Madugula
Manish Madugula

Reputation: 149

Couple of mistakes in your reg-ex you have to put '-' in front of charachter class (or at last).

Below reg-ex will do the trick

/[^.,\[\]\\'a-zA-Z0-9]/g

you can use online testers like http://www.regexpal.com/ to check regex's

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521229

In your original regex, your dash (hyphen) is being interpreted as a range:

[^a-zA-Z0-9'.-\[\], ]

This is being intepreted as the range of characters from dot . until opening bracket [, which includes the at symbol. If you move the hyphen to the very end of the negated character class, the regex will work as intended:

str = "hello@_";
str = str.replace(/[^a-zA-Z0-9'.\[\], -]/g,"#");
console.log(str);

Upvotes: 2

Related Questions