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

166
Views
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 answers
Answer question

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 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!