【发布时间】:2017-12-28 10:02:36
【问题描述】:
我正在尝试使用 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 函数没有被调用?
感谢您的帮助
【问题讨论】:
-
它不适用于
cssnew值regex101.com/r/iT2eR5/17 -
抱歉链接使用的是旧的 regx 它可以使用
@media[^{]+([\s\S]+})\s*TRY: regex101.com/r/r0sWeu/1 -
cssnew = cssnew.replace(/@media[^{]+([\s\S]+})\s*/g, '{ .foo $1}')。您在这里犯了几个非常常见的错误。 -
字符串是不可变的,这意味着您不能修改现有字符串,您只能使用修改创建一个新字符串。
replace()函数返回这个修改后的新字符串,但您没有对它做任何事情。
标签: javascript css regex string replace