繁体   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