简体   繁体   中英

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/

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM