[英]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.