2013-09-05 72 views
0

試圖將變量傳遞給一個強壯的正則表達式,我可以讓它在函數外部工作,但不知道如何讓它在函數內工作,或者它爲什麼匹配[1 ]似乎返回null。很多關於替換的信息,而不是關鍵字後的單詞。將變量傳遞到函數中的正則表達式

這裏是我

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); 

回答

0

不要把周圍/ S和逃避反斜槓(\):

new RegExp(theWord + "\\s(\\w*)"); 

var theWord = "hello"; 
var theRegEx = new RegExp(theWord + "\\s(\\w*)"); 
"hello world".match(theRegEx) // => ["hello world", "world"] 
+0

啊,這似乎工作。這是一個愚蠢的錯誤。謝謝。 – Lukasz

相關問題