我正在尝试使用Javascript解析媒体查询。
我希望标记字符串看起来像这样
@media not screen and (min-width: 700px) {
padding-left: 30px;
background: url(email-icon.png) left center no-repeat;
}
@media (max-width: 600px) {
color: red;
}
将输出:
@media not screen and (min-width: 700px) {
.foo{
padding-left: 30px;
background: url(email-icon.png) left center no-repeat;
}
}
@media (max-width: 600px) {
.foo{
color: red;
}
}
到目前为止,我有这个
const css = `@media (max-width: 600px) { color: red; }`
const pattern = new RegExp('@media[^{]+([\s\S]+})\s*')
const cssnew = css.replace( pattern, (full,match) => `{ .foo${match}}` );
// cssnew === "@media (max-width: 600px) { .foo{ color: red; } }"
这个正则表达式看起来像它在1(@media
)https://regex101.com/r/r0sWeu/1上工作,那没关系...但是未调用replace函数吗?
谢谢你的帮助
您需要按以下步骤修复代码:
const cssnew = ` @media (max-width: 600px) { color: red; }`
const pattern = /(@media[^{]+{\s*)([\s\S]+?)(\s*})/g
console.log(cssnew.replace( pattern, "$1.foo{\n\t\t$2\n\t}$3" ));
笔记:
/pattern/
,在这里您不需要将反斜杠加倍$1
将获取存储在组1中的值的反向引用即可。[\s\S]+
太贪婪了,起床了}
,使用懒惰的版本[\s\S]+?
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句