Javascript split string on space or on quotes to array

The accepted answer is not entirely correct. It separates on non-space characters like . and – and leaves the quotes in the results. The better way to do this so that it excludes the quotes is with capturing groups, like such:

//The parenthesis in the regex creates a captured group within the quotes
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = 'single words "fixed string of words"';
var myArray = [];

do {
    //Each call to exec returns the next regex match as an array
    var match = myRegexp.exec(myString);
    if (match != null)
    {
        //Index 1 in the array is the captured group if it exists
        //Index 0 is the matched text, which we use if no captured group exists
        myArray.push(match[1] ? match[1] : match[0]);
    }
} while (match != null);

myArray will now contain exactly what the OP asked for:

single,words,fixed string of words

Leave a Comment