I want to replace a substring in a text between two indexes. But I want to ignore any HTML tag when counting the index.
For example
If the text is the best kitchen knife I want to replace the substring from index 4 to 8 with 'nice' so the output should be the nice kitchen knife
But if the text is in HTML tag like
<li>the best kitchen knife</li>
or
<li>the <span>best</span> kitchen knife</li> and given indexes are 4 and 8, it should count from 'the' not from <li>. So the expected output should be <li>the <span>nice</span> kitchen knife</li>
I used the following code but it doesn't work as I'm expecting.
function replaceBetween(origin, startIndex, endIndex, insertion) {
return (
origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
);
}
Usage:
replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");
Output:
<li>nice<span>best</span> kitchen knife</li>
Expected Output:
<li>The <span>nice</span> kitchen knife</li>
One solution is to retrieve the .innerText of your li element. The returned value will not contain any html tags so you can manipulate the text as required. If the removed tags are needed, you'll have to put them back (by modifying the text string to include tags) and set the li element' .innerHTML` to your text string (where the browser will interpret the text as html markup).
The result of the .innerText retrieval is shown in the log of the following snippet:
let txt = document.getElementsByTagName('li')[0].innerText;
console.log(txt);
<ul>
<li>the <span style="color:red">best</span> kitchen knife</li>
</ul>