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;
Lorem Ipsum
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;") );