簡體   English   中英

如何將 HTML 元素(如“ <sup>X</sup> ”)替換為“(X)”等括號?

[英]How to replace HTML elements like `<sup>X</sup>` by parentheticals like `(X)`?

我有像這樣的 HTML - BLAH BLAH BLAH BLAH BLAH BLAH <sup>x</sup> - 在<th>內。

我正在嘗試用(x)替換<sup>x</sup>

這些都是我嘗試過的不同方法。 insideSup是字母。

newText = $(tableRow).find("th").eq(tdIndex)
  .text().replace("<sup>(.*?)</sup>", " ") + "(" + insideSup + ")";
newText = $(tableRow).find("th").eq(tdIndex)
  .html().replace("<sup>(.*?)</sup>", " ") + "(" + insideSup + ")";
newText = $(tableRow).find("th").eq(tdIndex)
  .find("sup").html().replace("/<sup>/g", " ") + "(" + insideSup + ")";
newText = $(tableRow).find("th").eq(tdIndex)
  .find("sup").html().replace("<sup>(.*?)</sup>", " ") + "(" + insideSup + ")";
newText = $(tableRow).find("th").eq(tdIndex)
  .text().find("sup").html().replace("<sup>(.*?)</sup>", " ") + "(" + insideSup + ")";

您已經擁有可用的 DOM。 根本不需要正則表達式 只需使用replaceWith方法

$(tableRow).find("th").eq(tdIndex).find("sup")
  .replaceWith((_index, textContent) => `(${textContent})`);

等效地,如果沒有 jQuery,假設tableRowHTMLTableRowElement ,使用同名方法

tableRow.querySelectorAll("th")[tdIndex].querySelectorAll("sup")
  .forEach((sup) => sup.replaceWith(`(${sup.textContent})`));

非常簡單,只需String.replace()

 let target = document.querySelector("div"); // Store the text (not HTML) in the sup let originalText = target.querySelector("sup").textContent; // Replace the sup element with the original content of the sup, // surrounded by () target.textContent = target.innerHTML.replace("<sup>x</sup>", "(" + originalText + ")");
 <div>BLAH BLAH BLAH <sup>x</sup></div>

您可以通過分別替換<sup></sup>來完成此操作。 您可以使用String.replace()方法來做到這一點,如下所示。

let text = "BLAH BLAH BLAH <sup>x</sup>";
let newText = text.replace("<sup>", "(").replace("</sup>", ")");

暫無
暫無

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

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