Skip to content Skip to sidebar Skip to footer

Javascript / Convert Css Style String Into Js Object

We'd like to convert a CSS style entered as string into a JS object. E.g., var input = ' border:solid 1px; color:red '; expected JS object : { border:'solid 1px', colo

Solution 1:

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

Solution 2:

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(':');
}

Solution 3:

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.

Solution 4:

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

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

Solution 5:

Stylesheet string to element style using JavaScript

Use just the string, CSSStyleDeclaration.cssText:

const styles = "color: black; background: orange; font-size: 2em;";
document.querySelector("#test").style.cssText = styles;
<divid="test">Lorem Ipsum</div>

JavaScript Implementation

otherwise, if you need to convert a style string to Object:

constcss2obj = css => {
	
  const r = /(?<=^|;)\s*([^:]+)\s*:\s*([^;]+)\s*/g, o = {};
  css.replace(r, (m,p,v) => o[p] = v);
  return o;
	
}

console.log( css2obj("z-index: 4; opacity:1; transition-duration: 0.3s;") )

In case you want to convert dash-case CSS properties to JS representations in camelCase, instead of p use p.replace(/-(.)/g, (m,p) => p.toUpperCase())


Oldschool JS:

functioncssToObj(css) {
    var obj = {}, s = css.toLowerCase().replace(/-(.)/g, function (m, g) {
        return g.toUpperCase();
    }).replace(/;\s?$/g,"").split(/:|;/g);
    for (var i = 0; i < s.length; i += 2)
        obj[s[i].replace(/\s/g,"")] = s[i+1].replace(/^\s+|\s+$/g,"");
    return obj;
}


console.log( cssToObj("z-index: 4; opacity:1; transition-duration: 0.3s;") );

Post a Comment for "Javascript / Convert Css Style String Into Js Object"