这可能是一个很容易回答的问题,但我还没有想出正确的方法是什么。
我需要使用 ^ 和 $
通过正则表达式匹配文本,以仅匹配以该字符串开头和结尾的元素。但是,我需要能够使用变量来做到这一点:
var name // some variable
var re = new RegExp(name,"g");
所以我想匹配每个完全包含(从头到尾)我的变量 name
的字符串,但我不想匹配在某个地方包含我的变量 的字符串姓名
。
我该怎么做?
谢谢
最佳答案
var strtomatch = "something";
var name = '^something$';
var re = new RegExp(name,"gi");
document.write(strtomatch.match(re));
i
用于忽略大小写。
这只匹配单词“something”,不会匹配其他内容。
如果你想在句子中间匹配它,你应该在你的代码中使用以下内容
var name = ' something ';
或者,使用单词边界,
var name = '\\bsomething\\b';
关于javascript - 使用 $ 和 ^ 的正则表达式中的变量匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489396/