CSS parsing with RegEx in JavaScript

I have been trying to compile a simple RegEx and Googling for the last hour, but I cannot find something that will work for me. I want to take a simple input line, for example ".cSSRule {value: 'foo';}" and break it into an array that looks like this: "[cssRule: value]", where the rule name is the key and the actual rule is the value. I am not looking for a full-fledged parser (although I know that they exist), because it will be redundant for the simple strings I work with. Would someone kindly point me in the right direction?

Thanks,

Blu

0
source share
3 answers

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 matched; the second (index 1) corresponds to all the conditions between the period and the open curly bracket, and the third (index 2) corresponds to everything that is between the curly braces.

+1
source

In this case, something like

 var str = ".cssRule { value: 'foo'; }"; someArray.push( ( (str.replace(/\.|}|;/g,'')) .split(/{/) .join(':"') .replace(/\s/g,'') .replace(/.$/,'"') ); /* =>"[cssRule:"value:'foo'"] */ 

will work. I do not think this is very general.

+2
source

Where does the input string come from? If this is a safe source (i.e., not coming from the user), just use the regular expression to separate the .cSSrule and eval() parts of the rest - you have your complete associative array parsed and created for you.

Edit: you need to replace ; on , except for the last appearance:

 input .replace(/^(.*)(?={)/, '') .replace(/;(?!(\s)*?})/g, ',') .replace(';', ''); myCss = eval(input); 
+1
source

Source: https://habr.com/ru/post/1392139/


All Articles