Home > Back-end >  JS - for each anchor link with specific URL in string, replace anchor link with its text
JS - for each anchor link with specific URL in string, replace anchor link with its text

Time:06-06

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?

CodePudding user response:

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);

  • Related