We\'d like to convert a CSS style entered as string into a JS object.
E.g.,
var input = \" border:solid 1px; color:red \";
expec
Use just the string, CSSStyleDeclaration.cssText:
const styles = "color: black; background: orange; font-size: 2em;";
document.querySelector("#test").style.cssText = styles;
<div id="test">Lorem Ipsum</div>
otherwise, if you need to convert a style string to Object:
const css2obj = 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:
function cssToObj(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;") );
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.
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;
}
This is my function to convert CSS string to object:
function cssConverter(style) {
var result = {},
attributes = style.split(';'),
firstIndexOfColon,
i,
key,
value;
for(i=0; i<attributes.length; i++) {
firstIndexOfColon = attributes[i].indexOf(":");
key = attributes[i].substring(0, firstIndexOfColon);
value = attributes[i].substring(firstIndexOfColon + 1);
key = key.replace(/ /g, "");
if(key.length < 1){
continue;
}
if(value[0] === " "){
value = value.substring(1);
}
if(value[value.length - 1] === " "){
value = value.substring(0, value.length - 1);
}
result[key] = value;
}
return result;
};