用 innerHTML 将标签替换为新标签以设置为 id

Replace tags with new tags with innerHTML to set to id

我有以下文字:

Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document

并想获得以下代码:

Send to <per>1</per> and <per>3</per> a new Document

标签之间的数字是身份证号码。

我找到了一个非常复杂的解决方案,例如:

function convert(f) {
    var str=f;
    str=str.replaceAll('<a class="', '[per]');
    str=str.replaceAll('/a>', '[/per]');
    str=str.replaceAll(/tipo\d/g, '');
    str=str.replaceAll(/['"]+/g, '');
    str=str.replaceAll('"', '');
    str=str.replaceAll(' id=', '');
    str=str.replaceAll(/\s*\>.*?\<\s*/g, "")
    str=str.replaceAll('[per]', '<per>');
    str=str.replaceAll('[/per]', '</per>');
    str=str.trim();
    document.getElementById('testoHTML').value=str;
}

但它给出了不同的问题。我知道它应该存在另一个使用正则表达式的解决方案,但我无法获得有效的结果。

希望找到一些好的解决方案:)

不清楚为什么在为 DOM 构建方法时使用正则表达式来更新 HTML。

const elems = document.querySelectorAll(".foo > a");
elems.forEach(elem => {
  const updateElem = document.createElement("p");
  updateElem.textContent = elem.id;
  elem.replaceWith(updateElem);
});
<div class="foo">Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document</div>

这似乎更像是 DOMParser 的工作:

var parsed = new DOMParser().parseFromString('Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document', "text/html");
parsed.querySelectorAll("a").forEach(e=>{
  n = document.createElement("pre");
  n.innerHTML  = e.id;
  e.replaceWith(n);
})
var result = parsed.body.innerHTML;
console.log(result);

需要指出的是,当您需要access/modifyHTML或XML时,不建议使用正则表达式。有关更多信息,请参见: RegEx match open tags except XHTML self-contained tags

也就是说,可以使用正则表达式达到如下结果:

find:
<a.+?id="([^"])+".+?/a>

re:
<per></per>

解释:

  • 找到'
  • 消耗所有字母直到找到'id="',然后消耗'id="'
  • 通过select搜索所有内容直到找到“””
  • ,将 id 的编号保存为第一组
  • 消费 '"' 和所有扩充结束 '/a>'
  • 最后,由于从开始''的所有内容都是select,因此将全部替换为'\1',其中\1是第一组的内容

我只是写了普通的正则表达式,因为你要求一个正则表达式解决方案。但是处理这个任务的正确方法是使用 DOM