首页 > 解决方案 > 如何用“(X)”之类的括号替换“ X ”之类的HTML元素?

问题描述

我有这样的 HTML - <code>BLAH BLAH BLAH <sup>x</sup> - 在<th>.

我正在尝试替换<sup>x</sup>(x).

这些都是我尝试过的不同方法。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 + ")";

标签: javascripthtmljqueryregexdom

解决方案


您已经拥有可用的 DOM。你根本不需要正则表达式。只需使用以下replaceWith方法

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

等效地,没有 jQuery,假设tableRow是一个HTMLTableRowElement,使用同名的方法

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

推荐阅读