Analysis Options Parameter

How can I parse a string like

Text = "Andrey \ Photos; Vacation"; Font = Arial; Size = 12

javascript object object, for example:

var options = { text: 'Andrey\ Photos; Vacation', font: 'Arial', size: 12 } 

My problem is that the value may contain characters ; and = , so I can’t just use s.split(';') . But if there are such characters in the value string, the value must be enclosed in single or double quotes. Therefore, parsing this line should be possible.

+4
source share
1 answer

Assuming the answer is no:

 var s = 'Text="Andrey\ Photos; Vacation";Font=Arial;Size=12;SingleQuoted=\'The dog said "Foo"\''; var re = /(.*?)=(?:"(.*?)"|'(.*?)'|([^;]*?))(?:;|$)/g; var match; var options = {} while(match = re.exec(s)) { var string_val = match[2] || match[3] || match[4]; var num_val = parseFloat(string_val); var val = isNaN(num_val) ? string_val : num_val; options[match[1].toLowerCase()] = val; } 

EDIT: Edited to allow the use of "or" as a delimiter. However, you still cannot escape.

EDIT 2: Edited to use the numeric type, if applicable. Now he just checks to see if he can be forced to a number, instead of looking at quotes.

+3
source

All Articles