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?开发者_高级运维
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. 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/
(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.
JSFiddle Example
Try this or something similar
var newString = cssProperties
.replace(":", ":'")
.replace(";", ", '");
var obj = eval(newString);
精彩评论