Search code examples
javascriptregexword-boundary

How do I use word boundaries in the RegExp object


What I want to know is how do I use word boundaries in the RegExp object.

For example:

var reg = new RegExp("\bAB\b", "g");

This is not working and I can't do:

var reg = /\bAB\b/g;

Since I will need to replace the AB with a variable later on.

I know all of the other things work in the RegExp object but for some reason word boundaries don't work. Thanks for any help on this issue. :)

Example: http://jsfiddle.net/7Kt5A/1/


Solution

  • Escape your backslashes with backslashes so the \b isn't interpreted as an escape character, but rather as a literal \b.

    var reg = new RegExp("\\bAB\\b", "g");
    reg.test(' AB ');
    // true
    reg.test('aABb');
    // false