首页 > 解决方案 > 如何在javascript中分离css代码块?

问题描述

如何在javascript中分离css代码块?

以下是序列化形式的一些 css:

const css = "body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }"

我如何解析它并以以下形式作为数组获取它(以及添加空格(保留空格。即格式化形式):

const parsedCss = [
'body {
  background-color: lightblue;
}',

'h1 {
  color: white;
  text-align: center;
}',

'p {
  font-family: verdana;
  font-size: 20px;
}',

]


标签: javascriptcsscodeblocks

解决方案


你可以使用const parsedCss = css.split(/(?<=\})/)

这会拆分“}”符号上的 css,并使用前瞻断言来保留它。

输出将是

[
'body {
  background-color: lightblue;
}',

'h1 {
  color: white;
  text-align: center;
}',

'p {
  font-family: verdana;
  font-size: 20px;
}',

]

推荐阅读