11

I want to use a string to perform a global regex, but it might have regex characters in it. What's the best way to escape all regex characters in a string before building a regex with it?

Basically I might have something like this;

var test = 'test.';
var regex = new RegExp(test, 'ig');

I need 'test.' to become 'test\.' so it doesn't behave in unexpected ways.

Andrew White
  • 52,720
  • 19
  • 113
  • 137
Stephen Belanger
  • 6,251
  • 11
  • 45
  • 49
  • Similar to a question I asked a few months ago! I never really got an answer though so maybe you will... http://stackoverflow.com/questions/3614440/replicate-the-functionality-of-javas-pattern-quote-in-a-javascript-regexp – Tyler Jun 09 '11 at 22:55

2 Answers2

20
new RegExp(test.replace(/[#-.]|[[-^]|[?|{}]/g, '\\$&'));

or simply:

new RegExp(test.replace(/[#-}]/g, '\\$&'));

the latter will end up escaping a lot more than it should, but it won't harm anything.

  • 1
    you forgot the /g global flag, to replace all the occurrences (I tried to edit your post, but it tells me that the change must be at least 6 characters) – youurayy Sep 24 '12 at 16:38
  • I had some issues with the second one (the regex would not match some things it should for some reason), but the first one works great! – Christian Bankester Dec 30 '14 at 17:13
  • Apparently, the short form doesn't work on Qt 5.15, so it might be a compatibility issue. – ratijas Nov 24 '21 at 03:19
2

This will replace all special RegExp characters with their escaped version:

test = test.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=\|]/ig, "\\$&");
mVChr
  • 49,587
  • 11
  • 107
  • 104
  • But some of those characters are only special in certain contexts, aren't they? Does that cause a problem at all? – Tyler Jun 09 '11 at 22:59
  • In other contexts escaping the character won't harm the RegExp match string, it will just end up being unnecessary. – mVChr Jun 09 '11 at 23:00
  • 1
    no need to escape `#`, `/`, `'` or `:`. You also need `-` and `,`, and you don't need to escape most of those characters in the context you're in. It can simply become `/[-\\.,_*+?^$[\](){}!=|]/` –  Jun 09 '11 at 23:11
  • Also no need for case insensitive `/ig` in answer just `/g`. @MarkKahn why comma and underscore? – Aaron Gillion Jun 07 '17 at 16:29
  • `,` is for repetition ranges: `{1,3}`. Not sure why I added an underscore, it was 6 years ago :D Seems unnecessary –  Jun 07 '17 at 18:57
  • btw, this is answered very similarly in the MDN docs, about mid-way down the page, as of today, here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-unicode-escape-es6 – keithpjolley Nov 15 '17 at 15:33