javascript中使用正则表达式清理table样式的代码

项目中遇到这样的需求,一大段文章正文的html代码在手机中显示不全,原因是由于其它有table,而table表格中的tr/td都携带了从word中粘贴过来的样式,需要将这一大段的字符串中的table、tr、td中携带的样式清除掉,同时还不能破坏table结构,即要保留tr中的rowspan和td中的colspan属性。

html部分代码如下:

<p><span lang="EN-US"> <o:p>文字中华人民共和国文字中华人民共和国文字中华人民共和国</o:p> </span></p> <table> <tbody> <tr> <td><p><span>项目<span lang="EN-US"> <o:p></o:p> </span></span></p></td> <td><p><span>金额<span lang="EN-US"> <o:p></o:p> </span></span></p></td> <td><p><span>经办人<span lang="EN-US"> <o:p></o:p> </span></span></p></td> <td><p><span>是否有发票<span lang="EN-US"> <o:p></o:p> </span></span></p></td> </tr> <tr> <td><p><span>合计<span lang="EN-US"> <o:p></o:p> </span></span></p></td> <td colspan="3" valign="bottom" nowrap=""><p><span lang="EN-US"> <o:p></o:p> </span></p></td> </tr> </tbody> </table> <p><span>文字中华人民共和国文字中华人民共和国文字中华人民共和国。</span><span lang="EN-US"> <o:p></o:p> </span></p>

JS脚本如下:

/* *格式化内容,str即是html格式的字符串 */ function formatContent(str){ str=str.replace(/<\/?(html|head|title|meta|body)\b[^>]*>/ig,""); str=str.replace(/<table[^>]*>/ig,"<table>"); return str; str=str.replace(/(<tr[^>]*>)/ig, function (a, b) { if(a.indexOf('rowspan')>-1){ a=a.replace(/([a-z]+)="([^"]+)?"/ig,function(c,d,e){ return d === 'rowspan' ? (d + '="' + e + '"') : ''; }) return a; }else{ return '<tr>'; } }); str=str.replace(/(<td[^>]*>)/ig, function (a, b) { if(a.indexOf('colspan')>-1){ a=a.replace(/([a-z]+)="([^"]+)?"/ig,function(c,d,e){ return d === 'colspan' ? (d + '="' + e + '"') : ''; }) return a; }else{ return '<td>'; } }); return str; }

脚本之家小编再给大家推荐一个

//表格替换 str=str.replace(/<table[^<>]*>/ig, "<table>"); str=str.replace(/<thead[^<>]*>/ig, "<thead>"); str=str.replace(/<tbody[^<>]*>/ig, "<tbody>"); str=str.replace(/<tfoot[^<>]*>/ig, "<tfoot>"); str=str.replace(/<tr[^<>]*>/ig, "<tr>"); str=str.replace(/<th [^<>]*>/ig, "<th>"); str=str.replace(/<td[^<>]*>/ig, "<td>"); str=str.replace(/<th>\s*?<p>/ig, "<th>"); str=str.replace(/<\/p>\s*?<\/th>/ig, "</th>"); str=str.replace(/<td[^<>]*>\s*?<p>/ig, "<td>"); str=str.replace(/<td>\s*?<p>/ig, "<td>"); str=str.replace(/<\/p>\s*?<\/td>/ig, "</td>");

这样对于表格中所有出现的标签都进行了替换,因为现在都是用css控制的,基本上不用这么多参数什么的了,除非特殊的表格

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdgsj.html