Javascript / convert CSS style string into JS object

后端 未结 10 983
粉色の甜心
粉色の甜心 2021-01-04 08:41

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

相关标签:
10条回答
  • 2021-01-04 09:18

    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;
    <div id="test">Lorem Ipsum</div>

    JavaScript Implementation

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

    0 讨论(0)
  • 2021-01-04 09:19

    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.

    0 讨论(0)
  • 2021-01-04 09:20

    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;
    }
    
    0 讨论(0)
  • 2021-01-04 09:20

    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;
    };
    
    0 讨论(0)
提交回复
热议问题