Question

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/

Was it helpful?

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

OTHER TIPS

You just need a couple of extra backslashes

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

Since it's a string, and a backslash escapes the following character, you'll have to escape the backslashes themselves.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top