html标签正则匹配相关

1. 匹配html标签的正则

/<[^>]+>/g

2. 匹配html标签内文本(只需要使用正向预查)

/[^<>]+(?=<)/g

3. 匹配html标签内以空格开始的文本

/\s+([^<>]+)(?=<)/g
/\s+(?:[^<>]+)(?=<)/g
/\s+[^<>]+(?=<)/g
/\s+(?=[^<>]+<)/g

4. 实例

1.该正则可匹配html标签内 空格+文本的内容,例如:测试 内容,匹配出来是 ' 内容'

let str = '<p style="text-align: center; "> 测试 内容</p>';
str = str.replace(/\s+([^<>]+)(?=<)/g, function (match) { return match.replace(/\s/g, '&nbsp;'); });

2.简单的,可以匹配html标签内文本,然后替换空格

let str = '<p style="text-align: center; "> 测试 内容</p>';
str = str.replace(/[^<>]+(?=<)/g, function (match) { return match.replace(/\s/g, '&nbsp;'); });

两个结果都是:

<p style=\"text-align: center; \">&nbsp;&nbsp;&nbsp;测试&nbsp;&nbsp;内容</p>

 

posted @ 2021-06-18 14:26  全玉  阅读(2430)  评论(0编辑  收藏  举报