[英]How to replace HTML elements like `<sup>X</sup>` by parentheticals like `(X)`?
I have HTML like this — BLAH BLAH BLAH <sup>x</sup>
— inside a <th>
.我有像这样的 HTML - BLAH BLAH BLAH BLAH BLAH BLAH <sup>x</sup>
- 在<th>
内。
I am trying to replace <sup>x</sup>
by (x)
.我正在尝试用(x)
替换<sup>x</sup>
。
These are all the different methods I have tried.这些都是我尝试过的不同方法。 insideSup
is the letter. 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 + ")";
You already have the DOM available to you.您已经拥有可用的 DOM。 You don't need regex at all.你根本不需要正则表达式。 Just use the replaceWith
method :只需使用replaceWith
方法:
$(tableRow).find("th").eq(tdIndex).find("sup")
.replaceWith((_index, textContent) => `(${textContent})`);
Equivalently, without jQuery, assuming tableRow
is an HTMLTableRowElement
, using a method with the same name :等效地,如果没有 jQuery,假设tableRow
是HTMLTableRowElement
,使用同名方法:
tableRow.querySelectorAll("th")[tdIndex].querySelectorAll("sup")
.forEach((sup) => sup.replaceWith(`(${sup.textContent})`));
Pretty straight-forward with just String.replace()
;非常简单,只需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>
You can accomplish this by replacing the <sup>
and </sup>
separately.您可以通过分别替换<sup>
和</sup>
来完成此操作。 You can do it by using String.replace()
method as shown below.您可以使用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.