简体   繁体   English

Javascript / 将CSS样式字符串转成JS object

[英]Javascript / convert CSS style string into JS object

We'd like to convert a CSS style entered as string into a JS object.我们想将作为字符串输入的 CSS 样式转换为 JS object。

Eg,例如,

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

expected JS object:预计 JS object:

 {
    border:"solid 1px",
    color:"red"
 }

Of course the number of style entries is unlimited as well as the names of style (border, color, font, z-index, etc...).当然,样式条目的数量以及样式名称(边框、颜色、字体、z-index 等)都是无限的。 Thx.谢谢。

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 https://regex101.com/r/nZ4eX5/1

You could use the Javascript split function: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split您可以使用 Javascript 拆分功能: 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.作为分隔符,然后对于每个结果用:分割,将项目放在一个对象中。

eg例如

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

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.在将字符串用作对象键之前对其进行修剪。

Stylesheet string to element style using JavaScript使用 JavaScript 将样式表字符串转换为元素样式

Use just the string, CSSStyleDeclaration.cssText :只使用字符串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 JavaScript 实现

otherwise, if you need to convert a style string to Object:否则,如果您需要将样式字符串转换为 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())如果您想将dash-case CSS 属性转换为camelCase JS 表示,而不是p使用p.replace(/-(.)/g, (m,p) => p.toUpperCase())


Oldschool JS:老派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;") );

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;
}

Just for fun and for completeness…只是为了好玩和完整……

I haven't checked cross-browser compatibility (only tried in Chrome), and it has some quirks:我没有检查跨浏览器兼容性(仅在 Chrome 中尝试过),它有一些怪癖:

var input = "font-weight:bold; color: blue; margin: 0 15px";

var e = document.createElement("div");
e.setAttribute("style", input);

var output = {};

for (var i = 0; i < e.style.length; i++) {
  var name = e.style[i];
  var value = e.style.getPropertyValue(name);
  output[name] = value;
}

The quirk is that even though we passed in a single margin declaration, we get an object like奇怪的是,即使我们传入了一个margin声明,我们也会得到一个像

{
  color: "blue",
  font-weight: "bold",
  margin-bottom: "0px",
  margin-left: "15px",
  margin-right: "15px",
  margin-top: "0px",
}

This might be a good or a bad thing depending on what you're after.这可能是好事也可能是坏事,这取决于您的追求。

If you want a tagged template literal syntax that works easily with React, you could do如果你想要一个易于与 React 一起使用的标记模板文字语法,你可以这样做

 const camelCase = str => str.replace(/-(.)/g, (_,p) => p.toUpperCase()) const css2obj = (strings, ...vals) => { const css = strings.reduce((acc, str, i) => acc + str + (vals[i] || ''), '') const r = /(?<=^|;)\\s*([^:]+)\\s*:\\s*([^;]+)\\s*/g, o = {} css.replace(r, (m,p,v) => o[camelCase(p)] = v) return o } const center = 'center' const reactInlineCSS = css2obj` align-items: ${center}; justify-content: ${center}; ` console.log(reactInlineCSS)

This is my function to convert CSS string to object:这是我将 CSS 字符串转换为对象的函数:

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;
};

Now you can use a third-party library such as style-to-object .现在您可以使用第三方库,例如style-to-object For example:例如:

import parse from 'style-to-object';

const input = " border:solid 1px; color:red ";
parse(input); // => {border: "solid 1px", color: "red"}

The following function works even when there are ;以下 function 即使有; inside single or double quotes.在单引号或双引号内。 Ex: content: "data;"例如: content: "data;" . .

function inlineStylesToObject(styles: string) : Record<string, string> {

  const regex = /([\w-]+)\s*:\s*((?:(?:"[^"]+")|(?:'[^']+')|[^;])*);?/g;

  const obj : Record<string, string> = {};

  let match;
  while (match = regex.exec(styles)) {
     obj[match[1]] = match[2].trim();
  }

  return obj;

}

something like this should get you pretty close:这样的事情应该让你非常接近:

var input = " border:solid 1px; color:red ";
var output = '{' + input.replace(/([\w-.]+)\s*:([^;]+);?/g, '\n    $1:"$2",') + '\n}';

...turns ...转身

" border:solid 1px; color:red "

into进入

{ 
    border:"solid 1px", 
    color:"red ",
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM