在Javascript中转换字符串的一部分

Codemeasandwich

我正在尝试使用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(@mediahttps://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" ));

笔记:

  • 在正则表达式构造函数中,反斜杠用于形成转义序列,并定义文字反斜杠,必须将其加倍使用regex文字会更容易/pattern/,在这里您不需要将反斜杠加倍
  • 新值应分配给您要修改的变量,因为JS中的字符串是不可变的
  • 如果您只想使用捕获组值,则无需在replace方法内部使用回调,只需使用$1将获取存储在组1中的值的反向引用即可
  • 同样,[\s\S]+太贪婪了,起床了},使用懒惰的版本[\s\S]+?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章