我有一个输入,我想匹配一个字符串列表,但我希望每行按顺序匹配每个输入字。
即
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)
澄清一下,我要问的是:
我尝试使用负面的后观来做所有这些,但似乎javascript无法处理这个问题,而且我找到的所有变通方法都不能使用一组单词或者需要反转要测试的字符串并使用负数向前看符号。我不认为这些解决方案中的任何一个都是理想的,因为我计划在50到500个字符串上运行此测试。
答案 0 :(得分:-1)
试试这个,请注意我的替换正则表达式是设计的:
"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;
})