如何将字符串与单词数组进行比较并突出显示匹配的字符串中的单词?

时间:2017-09-08 19:57:49

标签: javascript arrays string

我有这个问题,我有一系列像这样的词

let words = ['prueba', 'etiquetas'];

和我的字符串

let product = 'Prueba de etiquetas';

这个单词和字符串数组会一直不同,每个产品都包含自己的单词数组,我想知道字符串中的哪些单词并在字符串中突出显示这些单词,在这种情况下我想打印输出应该是product变量:

Prueba de 礼节

到目前为止,我的代码是

if (words.length) {

    for (let x = 0; x < words.length; x++) {

        if (product.toUpperCase().indexOf(words[x].toUpperCase()) !== -1) {

            //Here I need to hightligh the words in the string
        }
    }
}

但我不知道如何在product变量中做出改变,一些想法?难道我做错了什么?我希望你能帮助我,谢谢。

3 个答案:

答案 0 :(得分:3)

将数组转换为正则表达式,并使用String#Replace包含带有span的单词:

&#13;
&#13;
const words = ['prueba', 'etiquetas'];
const product = 'Prueba Pruebaa de etiquetas aetiquetas';

// convert the array to a regular expression that looks for any word that is found in the list, regardless of case (i), over all the string (g)
const regexp = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');

// replace the found words with a span that contains each word
const html = product.replace(regexp, '<span class="highlight">$&</span>');

demo.innerHTML = html;
&#13;
.highlight {
  background: yellow;
}
&#13;
<div id="demo"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这是一个没有正则表达式的解决方案:

let words = ['prueba', 'etiquetas'];
let product = 'Prueba de etiquetas';

words = words.map(function(word) { return word.toLowerCase(); });

product = product.split(' ').map(function(word) { 
             return words.indexOf(word.toLowerCase()) >= 0 ? '<b>'+word+'</b>' : word; 
          }).join(' ')

console.log(product);

答案 2 :(得分:1)

您可以使用正则表达式:

&#13;
&#13;
var words   = ["product", "words"],
    product = "This arrAy of wOrds aNd String wiLl be dIFferent all tiMe, evEry pRoduCt conTaiNs its own arRay oF words.";
    
var regex = new RegExp('(' + words.join('|') + ')', "ig");

document.body.innerHTML = product.replace(regex, "<b>$1</b>");
&#13;
&#13;
&#13;