Javascript: Dynamic Regular Expressions

While I was rewriting my tag-engine for weirdweirdworld for the third time I came across a problem which costed me a couple of hours to solve. I’m using dynamic RegExps in my Javascript which have to be created using the new RegExp(variable) constructor instead of writing /variable/. After looking through the web I also found a way to add special characters like ^ and $ to specify precisely what I want to match. The syntax for this is:

var myReg = new RegExp('^' + variable + '$');

But I wanted to match the word boundaries, the modifier for this would be ‘\b’ but it didn’t work like that:

var myReg = new RegExp('\b' + variable + '\b');

I couldn’t find anything useful about this in my Javascript books so I tried several alternations for myself. It turns out that the solution looks like this:

var myReg = new RegExp('\\b' + variable + '\\b');

I don’t know if anybody is aware of this, I wasn’t and I think it is kind of unexpected since the literal version of this /\\b/ would match a backslash followed by a ‘b’.

Anyway, I had to post it for people looking for the same thing. Does anyone know a book about Javascript that deals with dynamic RegExps properly? Javascript The Definite Guide by O’Reilly was missing that detail too.

Technorati Tags:

8 Responses to Javascript: Dynamic Regular Expressions

  1. Maybe backslashes are used as escape characters, enabling you to write ‘\” (string containing a single quote). Single backslashes have a special meaning, so we need to write it twice for the _meaning_ of “backslash”, just like in PHP?

  2. Daniel is right, but really, this has nothing to do with the RegExp constructor. Rather, you have to escape your backslashes because backslash is also a special character in JavaScript string literals. Hence, if you don’t escape them, JavaScript converts “\b” to just “b” before the RegExp constructor ever sees your regex. If, on the other hand, you were getting the value from a text input or anything else other than a string literal, you wouldn’t need the double escaping.

  3. This post saved me from hours of headache trying to figure out WHY var myReg = new RegExp(‘\b’ + variable + ‘\b’) was not working.


    I owe you a beer!

    • Hah after all those years I’m glad this is still helpful 🙂 Beer can be arranged if you’re ever in Berlin / Germany 🙂

  4. How can I use “var myReg = new RegExp(‘\\b’ + variable + ‘\\b’);” with case insensitive ( \i ) ?

  5. The following (using four escapes) works in my environment: Mac, safari Version 10.0.3 (12602.4.8)

    var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)

Leave a Reply

Your email address will not be published. Required fields are marked *