Share:

How to highlight a word in an HTML list form a string with JavaScript?


for(let i = 0; i < mostrarString.length; i++) {
    //break each sentence down to its own array of words
    let splitString = mostrarString[i].split(" "); 
    let rebuiltString = '';

    for(let j = 0; j < splitString.length; j++) {
        //if the word matches palabra variable and is the first occurrence in the sentence
        if(splitString[j] === palabra && splitString.indexOf(splitString[j]) === j){
            //wrap it in a span tag
            rebuiltString += `<span style="color:red">${splitString[j]}</span>`
        } else {
            //otherwise add to new string as is
            rebuiltString += splitString[j]
        }
        //add a space except after last word
        if(i !== splitString.length - 1) {
            rebuiltString += " "
        }
    }
    const newItem = document.createElement('li');
    //set the string as the innerhtml so the span tag renders
    newItem.innerHTML = rebuiltString; 
    document.getElementById('listaResultado').append(newItem);
}


Comments

Popular posts from this blog

Get Color From Pixel C# WPF | Saatody | Amit Padhiyar

Basic Audio Operations With MP3 And Wave Files Using NAudio C#

Create Drag And Drop Operation Between DevExpress GridControl And Custom WPF UI | Saatody | Amit Padhiyar