[英]passing variable into regular expression in a function
trying to pass a variable into a beefy regex, I can get it to work outside the function, but not sure how to get it to work within a function, or why it match[1] seems to be returning null. 尝试将变量传递到强大的正则表达式中,我可以让它在函数外部运行,但不确定如何使它在函数内部运行,或者不确定为什么match [1]返回空值。 Lots of info on replacing, but not on finding words after a keyword. 有关替换的大量信息,但不是有关在关键字后找到单词的信息。
here is what I have 这是我所拥有的
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);
Don't put surrounding /
s and escape backslashes ( \\
): 不要放在/
周围并转义反斜杠( \\
):
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.