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

1 に答える 1

0

前後の s を入れず、バックスラッシュ ( )/をエスケープします。\

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

var theWord = "hello";
var theRegEx = new RegExp(theWord + "\\s(\\w*)");
"hello world".match(theRegEx) // => ["hello world", "world"]
于 2013-09-05T15:30:10.187 に答える