Skip to content

Instantly share code, notes, and snippets.

Created July 10, 2012 22:11
Show Gist options
  • Save anonymous/3086540 to your computer and use it in GitHub Desktop.
Save anonymous/3086540 to your computer and use it in GitHub Desktop.
parseCSS.js // returns parsed CSS text as a JavaScript object
(function (global) {
function cssTextClean(cssText) {
return cssText
.replace(/\/\*[\W\w]*?\*\//g, '') // remove comments
.replace(/^\s+|\s+$/g, '') // trim trailing space
.replace(/\s*([:;{}])\s*/g, '$1') // trim trailing separator space
.replace(/\};+/g, '}') // remove extra separators
.replace(/([^:;{}])}/g, '$1;}') // add trailing separators
}
function parseCSS(css) {
return parseCSSToObject(cssTextClean(css), /([^{};]*)([;{}])/g, css = { selector: 'all', value: [] }), css;
}
function parseCSSToObject(css, cssRegExp, cssObject) {
for (var m, obj; (m = cssRegExp.exec(css)) != null;) {
if (m[2] == '{') cssObject.value.push(obj = { parent: cssObject, selector: m[1], value: [] }) && (cssObject = obj);
else if (m[2] == '}') cssObject = cssObject.parent;
else if (m[2] == ';') cssObject.value.push(m[1]);
}
}
global.parseCSS = parseCSS;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment