views:

233

answers:

2
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix

i want the array to be like: single, words, fixed string of words.

+5  A: 
str.match(/\w+|"[^"]+"/g)

//single, words, "fixed string of words"
S.Mark
+3  A: 

This uses a mix of split and regex matching.

var str = 'single words "fixed string of words"';
var matches = /".+?"/.exec(str);
str = str.replace(/".+?"/, "").replace(/^\s+|\s+$/g, "");
var astr = str.split(" ");
if (matches) {
    for (var i = 0; i < matches.length; i++) {
        astr.push(matches[i].replace(/"/g, ""));
    }
}

This returns the expected result, although a single regexp should be able to do it all.

// ["single", "words", "fixed string of words"]

Update And this is the improved version of the the method proposed by S.Mark

var str = 'single words "fixed string of words"';
var aStr = str.match(/\w+|"[^"]+"/g), i = aStr.length;
while(i--){
    aStr[i] = aStr[i].replace(/"/g,"");
}
// ["single", "words", "fixed string of words"]
Sean Kinsey
thank, i am going for the improved version
Remi