Issue with RegExp escape function - Javascript

Viewed 73

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 () * ? \ +

1 Answers

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.

Related