如何在javascript中按空格分割字符串,除非在"quote"之间出现空格?

Che*_*hev 5 javascript regex arrays string split

最终我试图改变这个:

var msg = '-m "this is a message" --echo "another message" test arg';
Run Code Online (Sandbox Code Playgroud)

进入这个:

[
    '-m',
    'this is a message',
    '--echo',
    'another message',
    'test',
    'arg'
]
Run Code Online (Sandbox Code Playgroud)

我不太确定如何解析字符串以获得所需的结果.这是我到目前为止:

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}', ' ');
});
Run Code Online (Sandbox Code Playgroud)

我认为这样可行,但是人类看起来像是一种变幻无常的向后完成我想要的方式.我相信你们比分割前创建一个占位符字符串要好得多.

Gam*_*ist 5

使用exec(),你可以在没有引号的情况下获取字符串:

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
Run Code Online (Sandbox Code Playgroud)