简体   繁体   English

Javascript将属性拆分为Object排除在字符串内

[英]Javascript Split properties into Object exclude inside Strings

What is the best method for splitting or extracting the css properties out of as string and into an object? 将css属性从字符串中拆分或提取到对象中的最佳方法是什么?

var cssProperties = 'background:green;content:"Content;";color:pink;';

The above should result in the following 以上应导致以下结果

var theObject = {
    background:'green',
    content:'"Content;"',
    color:'pink'
}

Unfortunately I can not just use a split(";") and cycle through the array due to the semicolon in the url. 不幸的是,由于URL中的分号,我不能只使用split(“;”)并在数组中循环。 I could create a giant loop that cycles through every character while skipping the ";" 我可以创建一个巨大的循环,在跳过每个字符的同时跳过“;” only while wrapped in quotes, but that seems kinda of wrong. 仅用引号引起来,但这似乎是错误的。

Is there a regex trick for this? 有正则表达式的窍门吗?

Optional: Also are there any really good regex websites. 可选:也有任何非常好的正则表达式网站。 I understand most of the syntax but there doesn't seem to be many practical really complicated examples on most of the websites I have found. 我了解大多数语法,但是在我发现的大多数网站上似乎没有很多实际的,非常复杂的示例。

Here is a fiddle further demonstrating the function: http://jsfiddle.net/ZcEUL/ 这是进一步说明该功能的小提琴: http : //jsfiddle.net/ZcEUL/

(function() {
    var div = document.createElement('div'),
        rprops =/[\w-]+(?=:)/g,
        rcamelCase = /-(\D)/g,
        fcamelCase = function(a,letter) {
                return letter.toUpperCase();
            };
    window['styleToObject'] = function(str) {
        var props = str.match(rprops),
            prop, i = 0,
            theObject = {};
        div.style.cssText = str;
        while (prop = props[i++]) {
            var style=div.style[prop.replace(rcamelCase,fcamelCase)];
            if (style) {
                theObject[prop] = style;
            }
        }
        return theObject;
    };
})();

Here was the solution I made regarding your first css string you had listed... Not the best but maybe it'll help spark some ideas. 这是我针对您列出的第一个CSS字符串提出的解决方案...虽然不是最好的方法,但也许会有助于激发一些想法。

JSFiddle Example JSFiddle示例

Try this or something similar 试试这个或类似的东西

var newString = cssProperties
                   .replace(":", ":'")
                   .replace(";", ", '");
var obj = eval(newString);

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

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