将 css 属性从字符串拆分或提取到对象中的最佳方法是什么?
var cssProperties = 'background:green;content:"Content;";color:pink;';
上面的结果应该是下面的
var theObject = {
background:'green',
content:'"Content;"',
color:'pink'
}
不幸的是,由于 url 中的分号,我不能只使用 split(";") 并循环遍历数组。我可以创建一个巨大的循环,在跳过“;”的同时循环遍历每个字符。只是用引号括起来,但这似乎有点不对。
有正则表达式技巧吗?
可选: 也有任何非常好的正则表达式网站。我了解大部分语法,但在我找到的大多数网站上似乎没有很多实用且非常复杂的示例。
最佳答案
这是进一步演示该功能的 fiddle :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;
};
})();
关于Javascript 将属性拆分为对象排除在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4038492/