How to separate css code blocks in javascript?

Viewed 127

How to separate css code blocks in javascript?

Following are some css in the serialised form:

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

How can I parse it and get it in the following form as array (along with adding whitespaces (preserving whitespaces. i.e. in formatted form):

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

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

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

]


3 Answers

You could use const parsedCss = css.split(/(?<=\})/)

This splits the css on the "}" symbol, and uses lookahead assertion to retain it.

The output would be

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

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

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

]

Try splitting with regex

/(?<=})\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; }' ]
*/



we can add \n for newline to get the formatted output:

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;
 },

*/

Related