Skip to content

Instantly share code, notes, and snippets.

@jihchi
Forked from jonathantneal/parseCSS.js
Created July 20, 2014 12:42
Show Gist options
  • Save jihchi/38283461e91ad9adb08f to your computer and use it in GitHub Desktop.
Save jihchi/38283461e91ad9adb08f to your computer and use it in GitHub Desktop.
(function (global) {
function clean(css) {
return css
.replace(/\/\*[\W\w]*?\*\//g, "") // remove comments
.replace(/^\s+|\s+$/g, "") // remove trailing spaces
.replace(/\s*([:;{}])\s*/g, "$1") // remove trailing separator spaces
.replace(/\};+/g, "}") // remove unnecessary separators
.replace(/([^:;{}])}/g, "$1;}") // add trailing separators
}
function refine(css, isBlock) {
return /^@/.test(css) ? (css = css.split(" ")) && {
"identifier": css.shift().substr(1).toLowerCase(),
"parameters": css.join(" ")
} : (isBlock ? /:$/ : /:/).test(css) ? (css = css.split(":")) && {
"property": css.shift(),
"value": css.join(":")
} : css;
}
function parse(css, regExp, object) {
for (var m; (m = regExp.exec(css)) != null;) {
if (m[2] == "{") object.block.push(object = {
"selector": refine(m[1], true),
"block": [],
"parent": object
});
else if (m[2] == "}") object = object.parent;
else if (m[2] == ";") object.block.push(refine(m[1]));
}
}
global.parseCSS = function (css) {
return parse(clean(css), /([^{};]*)([;{}])/g, css = { block: [] }), css;
};
})(this);
(function(e){function t(e){return e.replace(/\/\*[\W\w]*?\*\//g,"").replace(/^\s+|\s+$/g,"").replace(/\s*([:;{}])\s*/g,"$1").replace(/\};+/g,"}").replace(/([^:;{}])}/g,"$1;}")}function n(e,t){return/^@/.test(e)?(e=e.split(" "))&&{identifier:e.shift().substr(1).toLowerCase(),parameters:e.join(" ")}:(t?/:$/:/:/).test(e)?(e=e.split(":"))&&{property:e.shift(),value:e.join(":")}:e}function r(e,t,r){for(var i;(i=t.exec(e))!=null;)i[2]=="{"?r.block.push(r={selector:n(i[1],!0),block:[],parent:r}):i[2]=="}"?r=r.parent:i[2]==";"&&r.block.push(n(i[1]))}e.parseCSS=function(e){return r(t(e),/([^{};]*)([;{}])/g,e={block:[]}),e}})(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment