js实现字符串切分数组


有一个字符串var aString = '1 2 3 "3.1 3.2 3.3" 4 5';
现在要把字符串用空格分割成数组元素,但是""里面的不分割,组成[1,2,3,"3.1 3.2 3.3",4,5],这个怎么实现?

JavaScript

嘟嘟嘟5103 9 years, 1 month ago

突然间让我涌起了想写一段正则表达式的豪情,^^

@Zhuxy 提醒,修改代码如下:


 var aString = '1 2 3 "3.1 3.2 3.3" 4 5 "6 7"';

var result = aString.match(/\"\S[^\"]*\"|\S/g)
    .map(function(str) {
        return str.replace(/\"/g, '');
    });

console.log(result); //[ '1', '2', '3', '3.1 3.2 3.3', '4', '5', '6 7' ]

插着羽毛的猪 answered 9 years, 1 month ago

自己简单的写了下处理的方法。我的思路是:

  1. 先把字符串按照空格拆分为数组;

  2. 遍历数组,寻找数组中引号的开始和结束位置,把这中间的数据拼接为一个数据,存储到数组中;

  3. 非引号中间的数据,作为单独数据进行存储;

  4. 返回存储的数组。


 function wsplit(str){
    var st = str.split(' '); // 先按照空格拆分为数组
    var start=-1;
    var result = [], // 存储结果
        item='';     // 存储双引号中间的数据

    for(var i=0, t=st.length; i<t; i++){
        // 处理双引号中间的数据
        if((st[i]+'').indexOf('"')>-1 || start>-1){
            // 如果正好是双引号所在的数据
            if( (st[i]+'').indexOf('"')>-1 ){
                if(start==-1){
                    item += st[i]+' ';
                    start = i;
                }else{
                    // 引号结束时,把item上拼接的数据压到result中
                    item += st[i]+'';
                    result.push(item);
                    item = '';
                    start = -1;
                }
            }else{
                // 引号中间的数据
                item += st[i]+' ';
            }
        }else{
            // 引号两边的数据直接压入到数组中
            result.push(st[i]+'');
        }
    }
    return result;
}
var aString = '1 "2 3" "3.1 3.2 3.3" 4 5';
console.log( wsplit(aString) ); // ['1', '"2 3"', '"3.1 3.2 3.3"', '4', '5']

老哈Und answered 9 years, 1 month ago

Your Answer