let find_word="xyz"
let el=document.getElementById("text");
let arr = el.innerHTML.split(" ");
let newarr=[];
for (let i = 0; i < arr.length; i ) {
if (arr[i] === find_word) {
newarr[i] = `<span >${arr[i]}</span>`;
} else {
newarr[i] = arr[i];
}
}
el.innerHTML=newarr.join(" ")
I highlighted the two xyz's in the sentence but I can't highlight the others I need to highlight the xyz's in the li tags but not in the subtag
<div id="text"> Nature, in xyz broadest xyz
<ul>
<li>xyz</li>
<li>xyz</li>
</ul>
<sub>xyz</sub> <sub>xyz</sub> sense of world.</div>
Please give me a better example of doing this. I am not good at regex. I just know the basic regex. If regex can be a solution for this. suggest me some , please.
CodePudding user response:
Following your edits in the question, try this:
el.innerHTML.split(/\b/);
The thing is that "xyz" is not surrounded by spaces in the places you are missing.
\b indicates a word boundary, so it will capture your missing occurences.
Note that, depending on what you are doing, it might be not completely safe, e.g. if the li element could have things will likely get messed up.
Hope that helps...