【问题标题】:Transform part of a string in Javascript在 Javascript 中转换字符串的一部分
【发布时间】: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


【解决方案1】:

你需要修复代码如下:

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" ));

注意事项:

  • 在正则表达式构造函数中,反斜杠用于形成转义序列,并定义文字反斜杠it must be doubled。使用正则表达式文字 /pattern/ 更容易,您不需要将反斜杠加倍
  • 应将新值分配给您要修改为strings are immutable in JS 的变量
  • 如果您只想使用捕获组值,则无需在替换方法中使用回调,只需使用反向引用 $1 即可获取存储在组 1 中的值。
  • 另外,[\s\S]+ 太贪心了,起不来第一个},使用懒惰的版本,[\s\S]+?。

【讨论】:

  • 谢谢,但它与问题中的示例输出不匹配。我如何获得@media (max-width: 600px) { .foo { color: red; } }?
  • 您不能将嵌套字符与 JS 正则表达式匹配。您需要构建解析代码。您是否需要匹配从@media 和下一个{ 到下一个匹配的} 的所有内容?
  • 你需要匹配从@media 和下一个{直到下一个匹配}的所有内容吗?是的!
  • @codemeasandwich:您能否再次确认您尝试匹配的文本:1)regex101.com/r/oq9QJp/1 和 2)regex101.com/r/oq9QJp/2(这些不是解决方案,只需要澄清您需要分析的文本) .
  • @codemeasandwich 尝试cssnew.replace( pattern, "$1.foo{\n\t\t$2\n\t}$3" ); 与/(@media[^{]+{\s*)([\s\S]+?)(\s*})/g 模式。
【解决方案2】:

反斜杠也是字符串中的转义字符。将'@media[^{]+([\s\S]+})\s*' 更改为'@media[^{]+([\\s\\S]+})\\s*'

【讨论】:

  • 谢谢,但它与问题中的示例输出不匹配。我如何获得@media (max-width: 600px) { .foo { color: red; } }?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多