Joseph
Joseph

Reputation: 4715

Is it possible to replace an <a> tag to it's href link within a string without using innerHTML?

I have a JavaScript string that looks like this

const link = `
  Checkout My Cheat Sheet:

  <a target="_blank" href="https://tailwindcomponents.com/cheatsheet/"/>

  It's awesome
`;

I want to convert the above text to this

const link = `
  Checkout My Cheat Sheet:

  https://tailwindcomponents.com/cheatsheet/

  It's awesome
`;

Although I can use innerHTML, my text might contain other script tags, which might cause XSS.

Replacing <a> tag is enough for me right now.

Is there any possible string solution?

Upvotes: 1

Views: 650

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

DOMParser can safely parse HTML strings without any possibility of unsafe code execution:

const link = `
  Checkout My Cheat Sheet:

  <a target="_blank" href="https://tailwindcomponents.com/cheatsheet/"></a>

  It's awesome
`;
const doc = new DOMParser().parseFromString(link, 'text/html');
for (const a of doc.querySelectorAll('a')) {
  a.replaceWith(a.href);
}
console.log(doc.body.innerHTML);

Note that you do need a closing tag for the <a>.

Upvotes: 7

Related Questions