How do I split a string by space in javascript, except when the spaces occur between "quote"?

arrays, javascript, regex, split, string

Solution

with exec(), you can allready take the strings without the quotes :

var test="once \"upon a time\"  there was   a  \"monster\" blue";

function parseString(str) {
    var re = /(?:")([^"]+)(?:")|([^\s"]+)(?=\s+|$)/g;
    var res=[], arr=null;
    while (arr = re.exec(str)) { res.push(arr[1] ? arr[1] : arr[0]); }
    return res;
}

var parseRes= parseString(test);
// parseRes now contains what you seek

Problem

Ultimately I'm trying to turn this: ``` var msg = '-m "this is a message" --echo "another message" test arg'; ``` into this: ``` [ '-m', 'this is a message', '--echo', 'another message', 'test', 'arg' ] ``` I'm not quite sure how to parse the string to get the desired results. This is what I have so far: ``` var msg = '-m "this is a message" --echo "another message" test arg'; // remove spaces from all quoted strings. msg = msg.replace(/"[^"]*"/g, function (match) { return match.replace(/ /g, '{space}'); }); // Now turn it into an array. var msgArray = msg.split(' ').forEach(function (item) { item = item.replace('{space}', ' '); }); ``` I think that will work, but man does that seem like a fickle and backwards way of accomplishing what I want. I'm sure you guys have a much better way than creating a placeholder string before the split.

Original source

Related problems