I have HTML like this — BLAH BLAH BLAH <sup>x</sup>
— inside a <th>
.
I am trying to replace <sup>x</sup>
by (x)
.
These are all the different methods I have tried. insideSup
is the letter.
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. You don't need regex at all. Just use the replaceWith
method :
$(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 :
tableRow.querySelectorAll("th")[tdIndex].querySelectorAll("sup")
.forEach((sup) => sup.replaceWith(`(${sup.textContent})`));
Pretty straight-forward with just 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. You can do it by using String.replace()
method as shown below.
let text = "BLAH BLAH BLAH <sup>x</sup>";
let newText = text.replace("<sup>", "(").replace("</sup>", ")");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.