首页 > 解决方案 > 循环遍历字符串并动态插入属性 vanilla js

问题描述

我正在循环浏览一串 HTML 内容。

循环遍历所有标题并动态注入其文本的 id 标签。

我在服务器端(nodejs)这样做,所以它限制了我可以使用或想要使用的内容,而无需添加任何额外的库来做这件事。例如。jQuery,domParser

有没有更有效的方法来做到这一点?全部在一个循环中?

let str = "<h1>abc</h1><h2>xyz</h2><h3>aaa</h3><h1>aaaaa</h1>";

if (str.match(/<h1>(.*?)<\/h1>/g) !== null) {
  const h1Arr = str.match(/<h1>(.*?)<\/h1>/g).map(val => {
    return val.replace(/<\/?h1>/g, '');
  });

  str = str.replace(/<h1>/g, function() {
    return `<h1 id="${h1Arr.shift().replace(" ", "_")}">`;
  });
}

if (str.match(/<h2>(.*?)<\/h2>/g) !== null) {
  const h2Arr = str.match(/<h2>(.*?)<\/h2>/g).map(val => {
    return val.replace(/<\/?h2>/g, '');
  });

  str = str.replace(/<h2>/g, function() {
    return `<h2 id="${h2Arr.shift().replace(" ", "_")}">`;
  });
}

if (str.match(/<h3>(.*?)<\/h3>/g) !== null) {
  const h3Arr = str.match(/<h3>(.*?)<\/h3>/g).map(val => {
    return val.replace(/<\/?h3>/g, '');
  });

  str = str.replace(/<h3>/g, function() {
    return `<h3 id="${h3Arr.shift().replace(" ", "_")}">`;
  });
}

console.log(str)

标签: javascript

解决方案


虽然我强烈不建议为 xml 或 html 创建自定义解析器,但有许多边缘情况需要处理。有一种方法可以按原样简化代码。

let str = "<h1>abc</h1><h2>xyz</h2><h3>aaa</h3><h1>aaaaa</h1>",
    r = new RegExp(/<(.+?)>(.+?)<\/\1?>/mgi),
    res,
    new_str = "";

while (res = r.exec(str)) {
  new_str += compose(...res);
}

function compose(str, tag, text) {
  let cut = str.substr(tag.length + 1);
  return `<${tag} id="${text}"${cut}`;
}

console.log(new_str);

推荐阅读