Javascript / convert CSS style string into JS object

In a functional form:

var styleInput = " border:solid 1px; color:red ";

var result = styleInput.split(';').reduce(function (ruleMap, ruleString) {
    var rulePair = ruleString.split(':');
    ruleMap[rulePair[0].trim()] = rulePair[1].trim();

    return ruleMap;
}, {});

Trim the strings before using them as object keys.


You could use the Javascript split function: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

First split the string with ; as the separator, and then for each result split with :, placing the items in an object as you go.

e.g.

var result = {},
    attributes = input.split(';');

for (var i = 0; i < attributes.length; i++) {
    var entry = attributes[i].split(':');
    result[entry.splice(0,1)[0]] = entry.join(':');
}

All the answers seem to need a lot of splitting- why not do a match and get all the pairs in one go?

function cssSplit(str){
    var O= {},
    S= str.match(/([^ :;]+)/g) || [];
    while(S.length){
        O[S.shift()]= S.shift() || '';
    }
    return O;
}

A very simple one:

var regex = /([\w-]*)\s*:\s*([^;]*)/g;
var match, properties={};
while(match=regex.exec(cssText)) properties[match[1]] = match[2].trim();

https://regex101.com/r/nZ4eX5/1