[ACCEPTED]-How to properly escape characters in regexp-escaping

Accepted answer
Score: 33

\Q...\E doesn't work in JavaScript (at least, they 9 don't escape anything...) as you can see:

var s = "*";
print(s.search(/\Q*\E/));
print(s.search(/\*/));

produces:

-1
0

as 8 you can see on Ideone.

The following chars need 7 to be escaped:

  • (
  • )
  • [
  • {
  • *
  • +
  • .
  • $
  • ^
  • \
  • |
  • ?

So, something like this would 6 do:

function quote(regex) {
  return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}

No, ] and } don't need to be escaped: they 5 have no special meaning, only their opening 4 counter parts.

Note that when using a literal 3 regex, /.../, you also need to escape the / char. However, / is 2 not a regex meta character: when using it 1 in a RegExp object, it doesn't need an escape.

Score: 4

I'm just dipping my feet in Javascript, but 2 is there a reason you need to use the regex 1 engine at all? How about

var sNeedle = '*Stars!*';
var sMySTR = 'The contents of this string have no importance';
if ( sMySTR.indexOf(sNeedle) > -1 ) {
   //found it
}
Score: 1

I performed a quick Google search to see 8 what's out there and it appears that you've 7 got a few options for escaping regular expression 6 characters. According to one page, you can define 5 & run a function like below to escape 4 problematic characters:

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

Alternatively, you 3 can try and use a separate library such 2 as XRegExp, which already handles nuances you're 1 trying to re-solve.

Score: 0

Duplicate of https://stackoverflow.com/a/6969486/151312

This is proper as per MDN (see 1 explanation in post above):

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

More Related questions