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 strin
Solution 1:
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.
Solution 2:
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.
Solution 3:
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);
Post a Comment for "Parsing CSS String With RegEx In JavaScript"