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. 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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.