如何在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;
}',]


解决方法

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

这会在“}”符号上拆分css,并使用先行断言来保留它。

输出应为

[
'body {
  background-color: lightblue;
}','h1 {
  color: white;
  text-align: center;
}','p {
  font-family: verdana;
  font-size: 20px;
}',]
,

尝试使用正则表达式分割

/(?<=})\s+/

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

const beautifiedCss = css_beautify(css)

const parsedCss = beautifiedCss.split(/(?<=})\s+/)

console.log(parsedCss.join(',\n\n'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.0/beautify-css.js"></script>

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

let parsedCss = css
  .trim()
  .split("}")
  .map((word) => (word + "}").trim());
parsedCss.pop();

console.log(parsedCss);

/*
OUTPUT: 
[ 'body { background-color: lightblue; }','h1 { color: white; text-align: center; }','p { font-family: verdana; font-size: 20px; }' ]
*/



我们可以为换行符添加\n以获得格式化输出:

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

let parsedCss = css
  .trim()
  .split("}")
  .map((word) =>
    (word.replace(/[;]/gi,";\n").replace(/[{]/gi,"{\n") + "}")
      .trim()
      .toString()
  );
parsedCss.pop();

parsedCss.map((parsed) => console.log(parsed + ","));

/*
OUTPUT: 

body {
 background-color: lightblue;
 },h1 {
 color: white;
 text-align: center;
 },p {
 font-family: verdana;
 font-size: 20px;
 },*/