rust string str?你想在Rust学习吗?Go考虑简单字符串插值特性
大家好,我是煎鱼。在日常开发 Go 工程中,我们经常会用 fmt.Printf 或 fmt.Sprintf 去写类似的拼装字符串的业务。如下代码:fmt.Printf("Hello Gopher %s
顺晟科技
2022-10-14 10:55:05
120
我先有一段html字符串,我想把里面的div,h1类似的标签替换为p标签,例如:
<h1 style="font-size:10px;">这是标题</h1>
替换为:
<p>这是标题</p>
最好是 php 语言的。
正则匹配:
const reg = /<(?:h1|div).*?>\s*(.*?)\s*<\/(?:h1|div)>/gi;
上面的这个正则,目前只匹配h1
和div
标签。
测试:
const html = `<h1 style="font-size:10px;">
<span>这是标题</span>
</h1>
<div style="font-size:10px;">这是标题</div>`;
const formatTagToP = (html) => {
const reg = /<(?:h1|div).*?>\s*(.*?)\s*<\/(?:h1|div)>/gi;
return html.replace(reg, ($1, $2) => {
if ($1) {
return `<p>${$2}</p>`;
}
return $1;
});
};
formatTagToP(html); // '<p><span>这是标题</span></p>\n<p>这是标题</p>'
简单封装标签转换
var data = '<h1 style="font-size:10px;">转为p测试</h1><h2 style="font-size:10px;">转为span测试</h2>'
// => <p style="font-size:10px;">转为p测试</p><span style="font-size:10px;">转为span测试</span>
console.log("转换结果", demo(data))
function demo (html) {
const rules = {
'h1': 'p',
'h2': 'span'
}
for(const tag in rules) {
const regStr = `(<)(${tag})(.*?>.*?</)(${tag})(>)`
const reg = new RegExp(regStr, 'g')
html = html.replace(reg, function (_, $1, $2, $3, $4, $5) {
return $1 + rules[tag] + $3 + rules[tag] + $5
})
}
return html
}
26
2023-02
26
2023-02
30
2022-11
30
2022-11
29
2022-11
29
2022-11