精简html代码:高效去除html标签属性的实用技巧
Word文档转换为网页时,生成的HTML代码常常包含冗余属性和样式,影响后续处理。例如,Word表格转换后的HTML代码通常包含大量不必要的属性。 本文提供一种高效清除HTML标签属性的方法。
核心代码如下:
function removeAttributes(htmlString) { // 正则表达式匹配HTML标签和属性 const pattern = /<[^>]+?(s+[^>]*?)?>/gi; // 使用字符串替换清除匹配到的属性 const cleanString = htmlString.replace(pattern, (match) => { return match.replace(/(s+w+(=["'][^"']*["'])?)/gi, ''); }); return cleanString;}// 示例const htmlString = '<p class="my-class" style="color:red">This is a paragraph.</p>';const cleanedString = removeAttributes(htmlString);console.log(cleanedString); // <p>This is a paragraph.</p>
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。