Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 328
Shawn31313 Avatar asked Sep 15 '25 00:09

Shawn31313


1 Answers

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
like image 86
Michael Berkowski Avatar answered Sep 16 '25 14:09

Michael Berkowski