0

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 + ")";
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
phpwebdev
  • 103
  • 1
  • 10
  • None of your attempts actually contain regexes. `"(.*?)"` is a string, `/(.*?)<\/sup>/` is a regex; `"//g"` is a string, `//g` is a regex, and so on. `replace` matches strings _literally_. – Sebastian Simon Jul 01 '20 at 18:20

3 Answers3

1

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})`));
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
0

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

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>", ")");
tume
  • 1
  • 2