Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

80
Views
How to replace a substring between two indexes ignoring HTML tag in JavaScript

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!