使用强标记将字母换行,并按顺序给出一个单词列表

时间:2015-01-14 23:22:37

标签: javascript regex negative-lookbehind

我有一个输入,我想匹配一个字符串列表,但我希望每行按顺序匹配每个输入字。

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. 找到单词后,请使用强标记将其换行并从输入测试中删除该单词
  4. 继续下一个单词,依此类推
  5. 我尝试使用负面的后观来做所有这些,但似乎javascript无法处理这个问题,而且我找到的所有变通方法都不能使用一组单词或者需要反转要测试的字符串并使用负数向前看符号。我不认为这些解决方案中的任何一个都是理想的,因为我计划在50到500个字符串上运行此测试。

    Javascript: negative lookbehind equivalent?

1 个答案:

答案 0 :(得分:-1)

试试这个,请注意我的替换正则表达式是设计的:

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

修改

这是你想要的更多:

result

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