我有一个字符串helloreact
我希望删除color属性及其值,使所有其他样式在传递color时保持不变。 (来自所有跨度)
如果我传递font-weight,它必须移除所有font-weight及其值。
例如:假设当我传递“color”时,上面字符串的输出必须是:
Hello <span style="background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>
我尝试使用:
html = myString.replace(new RegExp(`\\s*${props}\\s*:[^;]*[;"]`, "ig"), "");
其中,props是我要移除的样式属性。 示例“颜色”
上面代码中的问题是它从背景颜色中移除颜色。
虽然使用正则表达式可能会有很长的路要走,但更好的做法是依赖经过验证的HTML解析器。 Web API有一个:DOMParser
:
null
function removeCSS(s, cssProp) {
let doc = new DOMParser().parseFromString(s, "text/html");
for (let elem of doc.querySelectorAll("*")) elem.style.removeProperty(cssProp);
return doc.body.innerHTML;
}
let s = `Hello <span style="color: rgb(241, 18, 45); background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>`;
let result = removeCSS(s, "color");
console.log(result);
我认为您可以使用html=mystring.replace(/(?<=“;s){props}\:[^;]*;/,”“);
(?<=“;s){props}
是一个查找断言,如果props在”; 或者一个空间。 这样,背景颜色就不会包含在匹配中。