[英]passing variable into regular expression in a function
尝试将变量传递到强大的正则表达式中,我可以让它在函数外部运行,但不确定如何使它在函数内部运行,或者不确定为什么match [1]返回空值。 有关替换的大量信息,但不是有关在关键字后找到单词的信息。
这是我所拥有的
var s = 'match my word after this word';
function returnWordAfter(theSentence, theWord){
var TheRegEx = new RegExp("/"+theWord+"\s(\w*)/");
var matches = theSentence.match(TheRegEx, '');
return matches[1];
}
var matchedWord = returnWordAfter(s, "this");
console.log(matchedWord);
不要放在/
周围并转义反斜杠( \\
):
new RegExp(theWord + "\\s(\\w*)");
var theWord = "hello";
var theRegEx = new RegExp(theWord + "\\s(\\w*)");
"hello world".match(theRegEx) // => ["hello world", "world"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.