javascript - 循环遍历字符串并动态插入属性 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)
解决方案
虽然我强烈不建议为 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);
推荐阅读
- python - Python 'Logger' 模块双重记录
- python-3.x - Improve speed of wikipedia.search with Python
- go - Add struct or pointer to struct to slice
- javascript - 方法未定义为函数(定义为一个)
- apache - Apache configuration for slim3 with ssl
- c++ - How to use a (while) loop and where to place it if eligible for all code
- python - Sending a mass-email with Python using data from several .txt files
- php - Nginx 404 Not Found when access module on yii2
- swift - Problem connecting outlets when UICollectionViewCell is in a xib
- ios - Objective-C - 滚动时 UISearchController 结果在 UISearchBar 上重叠