3

I have a regex I'm running to filter rows in a table. The filtering is done in Javascript.

I'm writing coffeescript, but a Javascript solution would be fine -- I can just translate it to coffeescript myself.

I have a value role that contains a string I want to filter on using a regex. The problem is the string role may or may not have embedded '+' signs in it. Plus signs are special characters for regex searches and need to be escaped in the search string.

I create the regex search string like this (coffeescript):

"^"+role+"$"

How can I preprocess role to escape any '+' signs so the regex works?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Kevin Bedell
  • 13,254
  • 10
  • 78
  • 114

1 Answers1

5

+ is far from the only character with special meaning. Here is a function that will escape all the necessary characters:

function regex_escape(str) {
    return str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&');
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592