如何比较字符串与单词数组并突出显示匹配字符串中的单词? [英] How to compare string with array of words and highlight words in string that match?

查看:254
本文介绍了如何比较字符串与单词数组并突出显示匹配字符串中的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,我有很多这样的单词

I have this issue, I have an array of words like this

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

和我的字符串

let product ='Prueba de etiquetas';

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

This array of words and string will be different all time, every product contains its own array of words, and I would like to know which of these words are in the string and highlight these words in the string, in this case when I want to print the productvariable the output should be:

Prueba de etiquetas

到目前为止,我的代码是

My code so far is this

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 变量中进行这种更改,有些想法吗?难道我做错了什么?希望您能帮助我,谢谢.

But I have no idea how to make that change in the product variable, some ideas? Am I doing something wrong? I hope you can help me, thanks.

推荐答案

将数组转换为正则表达式,然后使用

Convert the array to a regular expression, and use String#Replace to wrap the words with a span:

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;

.highlight {
  background: yellow;
}

<div id="demo"></div>

这篇关于如何比较字符串与单词数组并突出显示匹配字符串中的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆