簡體   English   中英

是否可以<a>在不使用 innerHTML 的情況下將標簽替換為字符串中的 href 鏈接?</a>

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

我有一個看起來像這樣的 JavaScript 字符串

const link = `
  Checkout My Cheat Sheet:

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

  It's awesome
`;

我想把上面的文字轉換成這個

const link = `
  Checkout My Cheat Sheet:

  https://tailwindcomponents.com/cheatsheet/

  It's awesome
`;

雖然我可以使用 innerHTML,但我的文本可能包含其他腳本標簽,這可能會導致 XSS。

替換<a>標簽對我來說已經足夠了。

有沒有可能的字符串解決方案?

DOMParser 可以安全地解析 HTML 字符串,沒有任何不安全代碼執行的可能性:

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

請注意,您確實需要<a>的結束標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM