首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript将空格或引号上的字符串拆分为数组

Javascript将空格或引号上的字符串拆分为数组
EN

Stack Overflow用户
提问于 2010-05-12 17:52:09
回答 5查看 26.3K关注 0票数 32
代码语言:javascript
复制
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix

我希望数组是这样的:

代码语言:javascript
复制
var astr = ["single", "words", "fixed string of words"];
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-05-12 17:55:53

代码语言:javascript
复制
str.match(/\w+|"[^"]+"/g)

//single, words, "fixed string of words"
票数 32
EN

Stack Overflow用户

发布于 2013-09-06 07:55:35

公认的答案并不完全正确。它以非空格字符分隔,如。并将引号留在结果中。为了排除引号,更好的方法是捕获组,如下所示:

代码语言:javascript
复制
//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所要求的内容:

代码语言:javascript
复制
single,words,fixed string of words
票数 37
EN

Stack Overflow用户

发布于 2014-07-02 04:36:46

这可能是一个完整的解决方案:https://github.com/elgs/splitargs

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2817646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档