2

我有一个输入,我想匹配一个字符串列表,但我想按每行的顺序匹配每个输入单词一次。

IE

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. 继续下一个单词,依此类推

我试图用负面的lookbehinds来做这一切,但似乎javascript无法处理这个问题,我能找到的所有解决方法要么不适用于单词集合,要么需要反转要测试的字符串并使用负面的lookaheads。我认为这些解决方案中的任何一个都不是理想的,因为我计划针对 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 回答