Reputation: 6052
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/
Upvotes: 4
Views: 281
Reputation: 18773
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.
Upvotes: 3
Reputation: 270637
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
Upvotes: 6