ic3 ic3 - 1 year ago 196
Javascript Question

Javascript / convert CSS style string into JS object

We'd like to convert a CSS style entered as string into a JS object.


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

expected JS object :

border:"solid 1px",

Of course the number of style entries is unlimited as well as the names of style (border, color, font, z-index, etc...). Thx.

Answer Source

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.


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(':');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download