有没有一种方法可以像我的示例中所示那样执行一步替换?
我知道,组用于类似的任务,但我不确定它们是否真的可以在这里工作。
var css = `
.foo { color: green; } // Invalid JS-style comment
.bar { color: yellow; } // Invalid JS-style comment
// Standalone invalid comment
.baz { color: red; } // Invalid JS-style comment
`;
// Is there a way to combine these two replacements in 1 step?
css = css.replace(/;/g, ' !important;');
css = css.replace(/\/\/.*/g, '');
alert(css);
最佳答案
假设在 ;
之后出现的只是右括号和注释,只需将所有内容替换为您需要的内容即可:
css.replace(/;.*/g, ' !important; }')
当然,如果您在一个 block 中有多个语句,它就不会工作。
关于您的编辑:然后您可以先匹配注释和可选的分号,但随后您需要使用替换功能,如下所示:
css.replace(/(;[^\/]*)?\/\/.*/g, (m, g) => g ? ' !important; }' : '');
它只匹配//或分号和注释,但只捕获后者。然后,它会检查是否捕获到某些内容,并仅在该情况下进行替换。
关于javascript - 将 2 个替换合并为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49961493/