我如何操作 javaScript 中的字符串?
How can i manipulate the string in javaScript?
我有一个字符串Hello <span style="color: rgb(241, 18, 45); background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>
我想删除颜色 属性 及其值,让所有其他样式在我传递颜色时保持原样。 (来自所有跨度)
如果我传递字体粗细,它必须删除所有字体粗细及其值。
例如:
可以说当我通过“颜色”时,
上述字符串的输出必须是:
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 解析器。网络 API 有一个:DOMParser
:
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}
是一个 Lookbehind 断言,如果 props 在 " 之后,它将匹配;或者 space。这样,背景颜色将不会包含在匹配中。
我有一个字符串Hello <span style="color: rgb(241, 18, 45); background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>
我想删除颜色 属性 及其值,让所有其他样式在我传递颜色时保持原样。 (来自所有跨度)
如果我传递字体粗细,它必须删除所有字体粗细及其值。
例如: 可以说当我通过“颜色”时, 上述字符串的输出必须是:
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 解析器。网络 API 有一个:DOMParser
:
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}
是一个 Lookbehind 断言,如果 props 在 " 之后,它将匹配;或者 space。这样,背景颜色将不会包含在匹配中。