0

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-

  • Number
  • Character (upper or lower case)
  • Any special character except -> comma, dot, square brackets, forward slash, single Quote

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

1
  • As it does in A-Z, the dash in .-[ is creating a range of characters Commented Jun 2, 2017 at 5:50

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

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

Comments

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.