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

173
Vistas
JS - for each anchor link with specific URL in string, replace anchor link with its text

To give an example of what I want, imagine this string:

$text = 'lorem ipsum <a href="/s/about">About us</a> lorem ipsum';

If this string contains an anchor link that has an href that starts with /, replace the entire anchor link with only its inner text. The result of this function would return the following:

lorem ipsum About us lorem ipsum

I've adapted a function I've used in the past for this purpose:

function replaceAnyQueriedElementByItsText(markup, selector) {
  const doc = (new DOMParser)
    .parseFromString(markup, "text/html");

  doc
    .body
    .querySelectorAll(selector)
    .forEach(node => node
      .parentNode
      .replaceChild(
        document.createTextNode(node.text),
        node,
      )
    );

  return doc.body.innerHTML;
}

The problem with this is that this expects a selector, such as a class. But what I want to select only anchors that have a specific href. How can I accomplish this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a[href^="/"] as selector. So as an argument to your function, it would be:

replaceAnyQueriedElementByItsText(markup, 'a[href^="/"]');

Example:

function replaceAnyQueriedElementByItsText(markup, selector) {
  const doc = new DOMParser().parseFromString(markup, "text/html");

  doc.body.querySelectorAll(selector).forEach(node => 
    node.parentNode.replaceChild(
        document.createTextNode(node.text),
        node,
    )
  );

  return doc.body.innerHTML;
}

// Example:
let markup = 'lorem ipsum <a href="/s/about">About us</a> lorem ipsum';
let stripped = replaceAnyQueriedElementByItsText(markup, 'a[href^="/"]');
console.log(stripped);

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