logo

JS正则匹配style,width,height等属性

2025-02-05 点击 49

JS正则匹配style,width,height等属性

window.onload = function() {
  var e = document.getElementById("str");
  var str = e.innerHTML;

  // 定义一个处理函数,用于移除指定属性
  function removeAttributes(html, attrName) {
    var regex = new RegExp('\\s' + attrName + '\\s*=\\s*("[^"]*"|\'[^\']*\')|\\s' + attrName + '\\s*=\\s*[^\\s>]+', 'ig');
    return html.replace(regex, '');
  }

  // 移除style, width, 和 height 属性
  str = removeAttributes(str, 'style');
  str = removeAttributes(str, 'width');
  str = removeAttributes(str, 'height');

  // 清理可能由于属性移除后留下的多余空格或不规范的标签闭合
  str = str.replace(/\s{2,}/g, ' ').trim(); // 去除多余的空格
  str = str.replace(/\s\/>/g, '/>'); // 确保自闭合标签正确

  e.innerHTML = str;
}
或者
window.onload = function() {
  var e = document.getElementById("str");
  var nodes = e.querySelectorAll('*'); // 获取所有子元素

  nodes.forEach(function(node) {
    node.removeAttribute('style');
    node.removeAttribute('width');
    node.removeAttribute('height');
  });
}

使用实例

图片自适应问题,保留宽度,删除高度


html部分

<body onload='clearheight()'>
<div id='con'>
<p>这里是内容,很多图片内容啊<p>
</div>
</body>

js部分
<script type="text/javascript"> 
function clearheight() 
{ 
  var e=document.getElementById("con"); 
  var scon=e.innerHTML; 
  scon = scon.replace(/\s+height\s*=\s*"[^"]*"|'[^']*'/ig, "");
  scon = scon.replace(/\s+height\s*=\s*[^>\s]+/ig, "");
  e.innerHTML = scon;
} 
</script> ​
0%