Got a little challenge parsing strings like:

Little brown="and yellow" fox=1 jumps over=lazy dog

I wanted to split it into an array with key/value pairs, so the result would be:

var res =
[ [ 'Little', undefined ],
  [ 'brown', 'and yellow' ],
  [ 'fox', '1' ],
  [ 'jumps', undefined ],
  [ 'over', 'lazy' ],
  [ 'dog', undefined ] ]

And here the regexp guy in me popped out and wanted to go for a short version. I ended up with

var text = 'Little brown="and yellow" fox=1 jumps over=lazy dog';

var res = text.match(/([^=\s]+="[^"]+")|\S+/g).map(function (p) {
    return p.match(/^([^=\s]*)(?:="?([^"]*)"?)?$/).splice(1, 2);


The first one (/([^=\s]+=”[^”]+”)|\S+/g) splits the string into an array of param|param=value|param=”value with space”. The second one (/^([^=\s])(?:=”?([^”])”?)?$/) split that array into separate arrays which contains key,value and remove the possible double quote on the value. Since match return all the splits, I splice out the values from the new array, 1 and 2.

And there you go.

You can find the last version at GitHub

PS: This rely on that exists, which it does in #nodejs

%d bloggers like this: