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
Post a Comment