[英]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. 我想知道的是如何在RegExp对象中使用单词边界。
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. 因为我稍后需要用变量替换AB。
I know all of the other things work in the RegExp object but for some reason word boundaries don't work. 我知道RegExp对象中的所有其他功能都有效,但由于某种原因,单词边界不起作用。 Thanks for any help on this issue.
感谢您对此问题的任何帮助。 :)
:)
Example: http://jsfiddle.net/7Kt5A/1/ 示例: 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
. 使用反斜杠转义反斜杠,因此
\\b
不会被解释为转义字符,而是解释为文字\\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. 因为它是一个字符串,并且反斜杠转义后续字符,所以你必须自己转义反斜杠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.