var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
我希望数组是这样的:
var astr = ["single", "words", "fixed string of words"];
发布于 2010-05-12 17:55:53
str.match(/\w+|"[^"]+"/g)
//single, words, "fixed string of words"
发布于 2013-09-06 07:55:35
公认的答案并不完全正确。它以非空格字符分隔,如。并将引号留在结果中。为了排除引号,更好的方法是捕获组,如下所示:
//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现在将包含OP所要求的内容:
single,words,fixed string of words
发布于 2014-07-02 04:36:46
这可能是一个完整的解决方案:https://github.com/elgs/splitargs
https://stackoverflow.com/questions/2817646
复制相似问题