简体   繁体   中英

How to compare string with array of words and highlight words in string that match?

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

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

and my string

let product = 'Prueba de etiquetas';

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 product variable 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
        }
    }
}

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> 

Here's a solution without regex:

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

You can use regex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM