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');
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’.
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?
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 🙂
How can I use “var myReg = new RegExp(‘\\b’ + variable + ‘\\b’);” with case insensitive ( \i ) ?
var myReg = new RegExp(‘\\b’ + variable + ‘\\b’, ‘i’)
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’)
posted in 2006 and iam learning it in 2021. that amazing. thanks for this post man