jquery - Javascript: split key value (with space) -
hi guys there way split string this:
var tmatch='key1="true" key2="group 1"';
in order obtain "true" , "group 1"?
i have tried this:
var key1; var key2; tmatch.split(' ').foreach(function(x){ var arr = x.split('='); if (arr[1]){ if (arr[0]=='key1'){ key1=arr[1]; }else if (arr[0]=='key2'){ key2=arr[1]; } } }); alert('key1:'+key1); alert('key2:'+key2);
but output key2 wrong , :
"group
instead of
"group 1"
because of space. can please suggest solution? thank in advance. please note key1 , key2 contain multiple spaces : key1="today nice day" key2="tomorrow not"
assuming can't have quotes inside strings, can using regexp.
var tmatch = 'key1="false" key2="group 1"'; var key1; var key2; var re = /(\w+)="([^"]*)"/g; while (match = re.exec(tmatch)) { if (match[1] == 'key1') { key1 = match[2]; } else if (match[1] == 'key2') { key2 = match[2]; } } alert('key1:' + key1); alert('key2:' + key2);
Comments
Post a Comment