How to capture css rule block in a string? This is too hard for me to capture, without the new line
.fa { color: red; }
small { font-size: 16px; }
#content { background-color: blue; }
What I want to accomplish is to get each those block into array
['.fa { color: red; }', 'small { font-size: 16px; }', '#content { background-color: blue; }']
Is this possible in javascript regex?
UPDATE
Sorry guys, I Thought this is only solvable with regex, But got an answer which is way simpler, Thanks
CodePudding user response:
Split by a closing curly brace:
const str = `.fa { color: red; }
small { font-size: 16px; }
#content { background-color: blue; }
`
const res = str.split("}").map(e => e = "}")
console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can match any sequence of characters that aren't a closing curly brace (}) up to the curly brace, as many times as there are. You might want to remove the newlines first, e.g.
let s = `.fa { color: red; }
small { font-size: 16px; }
#content { background-color: blue; }`;
console.log(s.match(/[^}]*}/g));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Of course malformed rules will cause an issue.
CodePudding user response:
const css = `.fa { color: red; }
small { font-size: 16px; }
#content { background-color: blue; }`;
const splitCSS = css.split(/\n/g);
there's a much simpler way...