Created
July 10, 2012 22:11
-
-
Save anonymous/3086540 to your computer and use it in GitHub Desktop.
parseCSS.js // returns parsed CSS text as a JavaScript object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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