2

文字列のリストに一致させたい入力がありますが、各入力単語を1行ごとに1回一致させたいと考えています。

いえ

var input = "One Two Three".split(" "),
    matchPattern = new RegExp('(' + input.join('|') + ')', 'i'); //Replace appropriately  

//Given the following, output as per comment

"One Two Three".replace(matchPattern, "<strong>$1</strong>"); 
//<strong>One Two Three</strong>    

"One One Three".replace(matchPattern, "<strong>$1</strong>"); 
//<strong>One</strong> One <strong>Three</strong>

"Two Three One".replace(matchPattern, "<strong>$1</strong>");
//<strong>Two Three</strong> One
//In this case: 
// match One if not after One Two or Three
// match Two if not after One Two or Three
// match Three if not after One or Three (Two already matched)

明確にするために、私が求めているのは次のことです。

  1. 文字列内の各単語を各入力単語でテストします
  2. 単語が見つかったら、強力なタグでラップし、入力テストからその単語を削除します
  3. 次の単語などに進みます

私はこれをすべて否定的な後読みで実行しようとしましたが、javascript はこれを処理できないようであり、私が見つけることができるすべての回避策は、単語のコレクションでは機能しないか、テストする文字列を逆にして否定的な先読みを使用する必要があります。50 ~ 500 個の文字列に対してこのテストを実行する予定であるため、これらのソリューションのいずれも理想的ではないと思います。

Javascript:負の後読みと同等ですか?

4

1 に答える 1

0

これを試してください、私の置換正規表現が不自然であることに注意してください:

"Two Three One".replace(/\b\w+\b/gi, "<strong>$&</strong>");

編集

これはあなたが望むものですか:

結果

var text = "Lorem ipsum  One Dolor Foo Two Bar Baz Three Lorem Three Quux One Two";
document.addEventListener('DOMContentLoaded', function() {
  var val = document.getElementById('myInput').value,
      aVals = val.match(/\b\w+/gi);

  aVals.forEach(function(val) {
    text = text.replace(new RegExp(val+'{1}', 'i'), '<span style="color: coral;">$&</span>' );
  });

  // console.log(), essentially
  document.body.innerHTML += text;
})
于 2015-01-14T23:25:22.077 に答える