Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda