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>