【问题标题】:How to replace HTML elements like `<sup>X</sup>` by parentheticals like `(X)`?如何用 `(X)` 之类的括号替换 `<sup>X</sup>` 之类的 HTML 元素?
【发布时间】:2020-10-22 05:32:45
【问题描述】:

我有这样的 HTML — BLAH BLAH BLAH &lt;sup&gt;x&lt;/sup&gt; — 在 &lt;th&gt; 中。

我正在尝试将&lt;sup&gt;x&lt;/sup&gt; 替换为(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 + ")";

【问题讨论】:

  • 您的所有尝试实际上都不包含正则表达式。 "&lt;sup&gt;(.*?)&lt;/sup&gt;" 是一个字符串,/&lt;sup&gt;(.*?)&lt;\/sup&gt;/ 是一个正则表达式; "/&lt;sup&gt;/g" 是一个字符串,/&lt;sup&gt;/g 是一个正则表达式,依此类推。 replace 匹配字符串字面意思。

标签: javascript html jquery regex dom


【解决方案1】:

您已经拥有可用的 DOM。你don’t need regex。只需使用replaceWith method:

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

等效地,没有 jQuery,假设 tableRow 是 HTMLTableRowElement,使用 method with the same name:

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

【讨论】:

    【解决方案2】:

    只需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 + ")");
    &lt;div&gt;BLAH BLAH BLAH &lt;sup&gt;x&lt;/sup&gt;&lt;/div&gt;

    【讨论】:

      【解决方案3】:

      您可以通过分别替换 &lt;sup&gt; 和 &lt;/sup&gt; 来完成此操作。您可以使用String.replace() 方法来完成,如下所示。

      let text = "BLAH BLAH BLAH <sup>x</sup>";
      let newText = text.replace("<sup>", "(").replace("</sup>", ")");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-19
        • 2019-11-23
        • 2012-08-27
        • 2022-06-22
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多