2

Trying to escape special characters. I type $ or ^ or | it works fine. Why is my below code not escaping () {} ? * + and \ when I type these I get invalid expression error.

escape = function(value) {
    return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}

something wrong with the above expression???

MDN suggests this

function escapeRegExp(string) {
  return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

even this I'm facing the same issue. no error for {} $ ^ | but I get error for () * ? \ +

2
  • 1
    They don't need to be escaped because they are inside a [ ] (which means they are part of a character class), if the were outside they would need to be escaped to be matched as normal characters. Commented May 8, 2020 at 2:19
  • So if I have to escape [ ] or ? or * I need to put them outside [ ]. Because when I type () or ? or + or * or \ I get the invalid regular exp error. I do not get that error for {} $ # | ^ Commented May 8, 2020 at 2:41

1 Answer 1

1

They're in a character class (denoted by []) meaning that they don't need to be escaped. They only need to be escaped when they're outside of a character class and in the regex, as they would denote certain operations (like {1,3} meaning "One to three times inclusive").

Also a small point of clarification for your question - the code's not escaping \, you're escaping \ by putting two of them together - \\ is the escape for \. So only {} and () are not being escaped, to answer the question at the top of your post.

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

1 Comment

ok I'm really confused Jack!!! When I type {} or $ or # or ^ or | no error is being thrown. But when I type () or ? or + or * or \ I get the invalid regular exp error. How did my function escape $ {} and all but not ? + \

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.