Parsing CSS string with RegEx in JavaScript
I have been trying to put together a simple RegEx and Googling for the last hour but I can't seem to find something that will work for me. I am looking to take a simple input string, say ".cSSRule { value: 'foo'; }" and split it into an开发者_如何学JAVA array that looks like this: "[cssRule:value]" where the name of the rule is the key and the actual rule is value. I'm not looking for a full-on parser (even though I know they exist) because that would be overkill for the simple strings that I am working with. Would anyone kindly point me in the right direction?
Thanks,
Blu
In this case something like
var str = ".cssRule { value: 'foo'; }";
someArray.push(
( (str.replace(/\.|}|;/g,''))
.split(/{/)
.join(':"')
.replace(/\s/g,'')
.replace(/.$/,'"')
);
/* =>"[cssRule:"value:'foo'"] */
would work. I don't think it's very generic though.
This should do it:
var str = ".cssRule { value: 'foo'; }";
var someObject = new Object;
var matches = str.match( /^\.(.*?){(.*?)}/ );
someObject[matches[1].replace(/ /g,'')] = matches[2].replace(/ /g,'');
'matches' becomes an array containing three elements: the first (index 0) is the full string of what it was matching against; the second (index 1) matches everything between a period and the open brace, and the third (index 2) matches everything between the braces.
Where is the input string coming from? If it's a safe source (i.e. not coming from the user) just use a regex to strip the .cSSrule
part and eval()
the rest -- you have your complete associative array parsed and created for you.
Edit: you'll need to replace ;
with ,
as well, except for the last occurence:
input
.replace(/^(.*)(?={)/, '')
.replace(/;(?!(\s)*?})/g, ',')
.replace(';', '');
myCss = eval(input);
精彩评论