
根据条件截取 html 字符串
在处理 html 字符串时,有时需要根据某些条件进行截取。本文将介绍如何使用正则表达式在 javascript 中根据条件拆分字符串,从而解决你遇到的问题。
问题:
有如下一段 html 代码:
立即学习“Java免费学习笔记(深入)”;
<h1</h1></h1><p><hr></p><p></p><h2 align="center"><hr></h2>
需要根据
["<h1</h1></h1><p><hr></p><p></p>", "<h2 align="center"><hr></h2>"]
解决方案:
可以使用正则表达式在 "h" 之前添加条件,来区分不同的标题标签。具体代码如下:
let txt = '<h1</h1></h1><p><hr></p><p></p><h2 align="center"><hr></h2>'; let result = txt.split(/(?=<h\d)/g); console.log(result);
结果:
["<h1</h1></h1><p><hr></p><p></p>", "<h2 align="center"><hr></h2>"]
解析:
正则表达式中,(?= 因此,该正则表达式会匹配每个


















