javascript - 如何用“(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 + ")";
解决方案
您已经拥有可用的 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})`));
推荐阅读
- csvhelper - 上传后使用块和删除文件时封闭 csv.Reader 的问题
- excel - AutoHotKey - 如何获取列中最后使用的行的行号(自下而上)?
- node.js - Express:从 Content-Type "application/json; charset=utf-8" 中删除 charset=utf-8
- r - 进行方差测试时出错
- java - 为什么我在java中陷入了一个超长的for循环?
- javascript - 您托管的文件上的浏览器缓存
- c# - 将图标附加到 listView 中的日期字符串格式
- java - 如何传递参数弹簧批处理Intellij maven
- laravel - 如何强制更新vue数据
- javascript - 自定义 React 组件(react-hook)不重新渲染