views:

62

answers:

3

What is the best method for splitting or extracting the css properties out of as string and into an object?

var cssProperties = 'background:green;content:"Content;";color:pink;';

The above should result in the following

var theObject = {
    background:'green',
    content:'"Content;"',
    color:'pink'
}

Unfortunately I can not just use a split(";") and cycle through the array due to the semicolon in the url. I could create a giant loop that cycles through every character while skipping the ";" only while wrapped in quotes, but that seems kinda of wrong.

Is there a regex trick for this?

Optional: Also are there any really good regex websites. I understand most of the syntax but there doesn't seem to be many practical really complicated examples on most of the websites I have found.

A: 

Here was the solution I made regarding your first css string you had listed... Not the best but maybe it'll help spark some ideas.

JSFiddle Example

subhaze
A: 

Try this or something similar

var newString = cssProperties
                   .replace(":", ":'")
                   .replace(";", ", '");
var obj = eval(newString);
Slappy
+1  A: 

Here is a fiddle further demonstrating the function: http://jsfiddle.net/ZcEUL/

(function() {
    var div = document.createElement('div'),
        rprops =/[\w-]+(?=:)/g,
        rcamelCase = /-(\D)/g,
        fcamelCase = function(a,letter) {
                return letter.toUpperCase();
            };
    window['styleToObject'] = function(str) {
        var props = str.match(rprops),
            prop, i = 0,
            theObject = {};
        div.style.cssText = str;
        while (prop = props[i++]) {
            var style=div.style[prop.replace(rcamelCase,fcamelCase)];
            if (style) {
                theObject[prop] = style;
            }
        }
        return theObject;
    };
})();
Lime
+1 much better solution than mine. Though it failed getting background-color in IE because it didn't recognize it as a style. I updated your fiddle to camelCase the props and it worked in chrome/IE/opera/FF/safari but the props with a '-' become camelCased... http://jsfiddle.net/subhaze/ACH9M/1/
subhaze
Update: preservers the '-' for the object: http://jsfiddle.net/subhaze/ACH9M/2/
subhaze
Sweet! I had completely forgotten about camelCase in IE. One edit though. We can either move div var into the the styleToObject function or we need to delete setting div = null. Just try running the styleToObject function twice. It will through an error the 2nd time.
Lime
Ah, good catch. I went ahead and updated moving div into the function so it's all one block. I also left the div = null not sure if that's needed for garbage collection or not though... http://jsfiddle.net/subhaze/ACH9M/3/
subhaze