gpt4 book ai didi

javascript - 给定单词列表一次并按顺序将单词包装在带有强标签的字符串中

转载 作者:行者123 更新时间:2023-11-30 06:53:10 25 4
gpt4 key购买 nike

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

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: negative lookbehind equivalent?

最佳答案

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

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

关于javascript - 给定单词列表一次并按顺序将单词包装在带有强标签的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27954319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com