I've used this in the past, but only when I knew exactly what I would be sending into the regexp - mainly because I'm sure there will be syntax out there that could break it (especially with the likes of mixins, css animations, css variables, and media queries). It's for these reasons why you should probably follow Mario's answer.
However, it has worked on the majority of my own css files that I've thrown at it and may help others out there... It isn't tailored to work with an array structure like you are using though, but that could be easily changed. Obivously you could optimise things by getting rid of RegExp and just using indexOf as shhac has done, but I find the expressiveness of RegExp far easier to work with and far easier to extend if and when you need to.
A few notes
- It assumes there are no comments in the CSS - you could always add a replace to strip comments.
- It relies on JSON.parse method being available - you could always include a non JSON fallback.
The code with comments:
window.onload = function(){
/// this is designed to find a <style> element in the page with id="css"
var entireStylesheetString = document.getElementById('css').innerHTML;
var css = String('{'+entireStylesheetString+'}')
/// convert double quotes to single to avoid having to escape
.replace(/"/gi,"'")
/// replace all whitespace sequences with single space
.replace(/\s+/g,' ')
/// sort the first open brace so things are neat
.replace(/^{/,'{\n')
/// sort the newlines so each declaration is on own line
.replace(/\}/g,'}\n')
/// find the selectors and wrap them with quotes for JSON keys
.replace(/\n\s*([^\{]+)\s+?\{/g,'\n"$1":{')
/// find an attribute and wrap again with JSON key quotes
.replace(/([\{;])\s*([^:"\s]+)\s*:/g,'$1"$2":')
/// find values and wrap with JSON value quotes
.replace(/":\s*([^\}\{;]+)\s*(;|(\}))/g,'":"$1",$3')
/// add commas after each JSON object
.replace(/\}/g,'},')
/// make sure we don't have too many commas
.replace(/,\s*\}/g,'}');
/// remove the final end comma
css = css.substring(0,css.length-2);
try{
/// parse using JSON
console.log(JSON.parse(css));
}catch(ee){
console.log(ee);
}
};
The code by it's lonesome:
window.onload = function(){
var entireStylesheetString = document.getElementById('css').innerHTML;
var css = String('{'+entireStylesheetString+'}')
.replace(/"/gi,"'")
.replace(/\s+/g,' ')
.replace(/^{/,'{\n')
.replace(/\}/g,'}\n')
.replace(/\n\s*([^\{]+)\s+?\{/g,'\n"$1":{')
.replace(/([\{;])\s*([^:"\s]+)\s*:/g,'$1"$2":')
.replace(/":\s*([^\}\{;]+)\s*(;|(\}))/g,'":"$1",$3')
.replace(/\}/g,'},')
.replace(/,\s*\}/g,'}');
css = css.substring(0,css.length-2);
try{console.log(JSON.parse(css));}catch(ee){console.log(ee);}
};