views:

44

answers:

1

I have a string that represents a list of tags separated by space. It may look like this:

Australia 2010 David November Family

If a tag contains at least one space, it must be quoted. So the string can be:

"Best Friends" "My Pictures" Wow "Very Nice Photo" University

Quotes are also allowed for single words. For example:

"Good One" Fantastic "February" "My Family" "Friends"

The question is:
How would you get an array of tags from the string ?
For example, from the third string I would like to get the following array:

arr[0] = "Good One"
arr[1] = "Fantastic"
arr[2] = "February"
arr[3] = "My Family"
arr[4] = "Friends"

If the string is not in the right format, I would like to know about it (for example: to get empty array as a result).

+3  A: 

You can use a regular expression like /"[^"]+"|\w+/ to match the tags. To get an array containing all the matches without quotation marks, you can use something like

var re = /"[^"]+"|\w+/g;
var result = [];
var match;
while(match = re.exec(input))
    result.push(match[0].replace(/"/g, ""));

If you don't have to remove the quotation marks, you can just use

var result = input.match(re);
Ventero
`/"[^"]+"|\S+/g` would add support for any character in unquoted strings