Skip to content

Instantly share code, notes, and snippets.

@remy
Created January 31, 2011 17:24
Show Gist options
  • Save remy/804414 to your computer and use it in GitHub Desktop.
Save remy/804414 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