javascript正则表达式,用于编辑元素内部的css样式属性

javascript regular expression to edit css style attributes inside of an element

本文关键字:css 样式 属性 内部 元素 正则表达式 用于 编辑 javascript      更新时间:2023-09-26

我正在编写一个javascript代码,它将操作/处理html内容,该内容具有内联css。我只需要对css内容进行更改。我有一个类似的html代码/字符串

<div style="height:20px;color:yellow;">&nbsp; and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here &gt;</p></div>

现在我想添加'!"important"标记到css参数,而不是到html特殊字符。结果应为

<div style="height:20px !important;color:yellow !important;">&nbsp; and some special characters here</div>
<div style="width: 200px !important;color:red !important;"><p style="font-size: 20px !important;">some content here &gt;</p></div>

这个的正则表达式是什么?我试过像这个

var str='<div style="height:20px;color:yellow;">&nbsp; and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here &gt;</p></div>'
var str2 = str.replace(';', ' !important;')

结果是

<div style="height:20px !important;color:yellow !important;">&nbsp !important; and some special characters here</div> <div style="width: 200px !important;color:red !important;"><p style="font-size: 20px !important;">some content here &gt !important;</p></div>

我知道这不是正确的,因为它用"!importanr;"替换了所有分号(;)。如果有人能给我一个只改变风格内部内容的正则表达式,我将不胜感激

请注意,我不是在网页/DOM上做这件事的。提前谢谢。

Regex/(?=[^<>]+:|'s*")/g

用法

var str='<div style="height:20px;color:yellow;">&nbsp; and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here &gt;</p></div>'
var str2 = str.replace(/;(?=[^<>]+:|'s*")/g, ' !important;')

Fiddle

var divElements = document.querySelectorAll("div"); // reference of div
var regPattern = /(?:(.*?);)/gm; // regex
for(var i = 0, len = divElements.length; i< len; i++) {

    var divElementCss = divElements[i].style.cssText; // getting the css alone

     divElementCss = divElementCss.replace(regPattern, "$1 !important;"); 
     // adding !important
     divElements[i].style.cssText = divElementCss; // replace again 
}