正则表达式替换HTML标记

时间:2014-11-07 09:43:30

标签: javascript html regex

有正则表达式的一些问题。 我有很长的字符串

str = '<div class=\"edit\">some text here
   <div><br></div>
   <div>then other row</div>
   <div><br></div> 
   <div>and one more</div>
</div>
<div class=\"edit\">some text here
<div><br></div><div>then other row</div></div>'

我希望:

<div class\"edit\">some text here<br>then other row<br>and one more<div>
<div class=\"edit"\>some text here<br>then other row<div>

我试着这样做:

str = str.replace(/<div><br><\/div>/ig, "<br>");
str = str.replace(/<div>/ig, "<br>");
str = str.replace(/<\/div>/ig, "");

1 个答案:

答案 0 :(得分:0)

一般来说,使用regexp转换html字符串是个坏主意。这有DOM。不过这个似乎有用:

str = str.replace(/<div><br><\/div>/gi, '<br>')
         .replace(/<div>([^<]*)<\/div>/gi, '$1');

结果字符串为"<div class="edit">some text here <br> then other row <br> and one more</div><div class="edit">some text here<br>then other row</div>"