title: Parsing CSS in JavaScript / jQuery
body: <p>I'm trying to implement parsing of CSS in JavaScript so that:</p>
  
  <pre><code>a {
    color: red;
  }
  </code></pre>
  
  <p>is parsed into the object:</p>
  
  <pre><code>{
    'a' {
      'color': 'red'
    }
  }
  </code></pre>
  
  <p>First off, is there a JavaScript / jQuery <strong>library</strong> I can use?</p>
  
  <p>My implementation is pretty basic, so I'm sure it is not fool-proof by any means. For example, it works fine for basic CSS, but for a property of the type:</p>
  
  <pre><code>background: url(data:image/png;base64, ....);
  </code></pre>
  
  <p>It fails because I am using <code>split(';')</code> to separate <code>property:value</code> pairs. Here, <code>;</code> occurs in the <code>value</code>, so it splits at that point too.</p>
  
  <p>Is there an alternate way to do this?</p>
  
  <p>Here is the code:</p>
  
  <pre><code>parseCSS: function(css) {
      var rules = {};
      css = this.removeComments(css);
      var blocks = css.split('}');
      blocks.pop();
      var len = blocks.length;
      for (var i = 0; i &lt; len; i++)
      {
          var pair = blocks[i].split('{');
          rules[$.trim(pair[0])] = this.parseCSSBlock(pair[1]);
      }
      return rules;
  },
  
  parseCSSBlock: function(css) { 
      var rule = {};
      var declarations = css.split(';');
      declarations.pop();
      var len = declarations.length;
      for (var i = 0; i &lt; len; i++)
      {
          var loc = declarations[i].indexOf(':');
          var property = $.trim(declarations[i].substring(0, loc));
          var value = $.trim(declarations[i].substring(loc + 1));
  
          if (property != "" &amp;&amp; value != "")
              rule[property] = value;
      }
      return rule;
  },
  
  removeComments: function(css) {
      return css.replace(/\/\*(\r|\n|.)*\*\//g,"");
  }
  </code></pre>
  
  <p>Thanks!</p>