Skip to content

Instantly share code, notes, and snippets.

@theophani
Forked from remy/gist:804414
Created August 3, 2011 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theophani/1122508 to your computer and use it in GitHub Desktop.
Save theophani/1122508 to your computer and use it in GitHub Desktop.
Simple CSS parser
function parseCSS(str) {
function trim(str) {
return (str||'').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
var i, j, k,
split = '}',
cur_key = '',
cur_key_split,
css = str.replace(/\t*/g, '').replace(/\s{2}/, ' ').replace(/[\n|\r]/g, ' ').replace(/\/\*.*?\*\//g, '').split(split),
css_obj = {};
for (i = 0; i < css.length; i++) {
// we're using .replace to construct and pass
// through matched values to construct our css object
if (css[i].replace( /^\s+|\s+$/g, '' ) === '') {
continue;
}
css[i].replace(/\/\*.*?\*\//, '')
.replace(/.*?\s*\{/, function(m,l){
cur_key = m.replace(/\s*\{$/,'').replace( /^\s+|\s+$/g, "" ).toLowerCase();
css_obj[cur_key]={};
return '';
}).replace(/(.*?;|.*$)/g, function(m,l) {
var v=m.replace(/;$/,'').split(/:/);
if (v[0]) css_obj[cur_key][trim(v[0])] = trim(v[1]);
});
// check for multiples, i.e. DIV > A, P > A => [DIV > A] = x, [P > A] = x
if (cur_key.indexOf(',') !== -1) {
cur_key_split = cur_key.split(/\s*,\s*/);
for (j = 0; j < cur_key_split.length; j++) {
css_obj[cur_key_split[j]] = css_obj[cur_key];
}
// delete the original mangled selector
delete css_obj[cur_key];
}
}
return css_obj;
}
/**
TODO
- expand shorthand styles (font, background, border, etc)
- expand shorthand colours?
- support @link (for same domain using XHR or XHR2 for x-domain...if we're lucky)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment