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],这个怎么实现?
Answers
自己简单的写了下处理的方法。我的思路是:
-
先把字符串按照空格拆分为数组;
-
遍历数组,寻找数组中引号的开始和结束位置,把这中间的数据拼接为一个数据,存储到数组中;
-
非引号中间的数据,作为单独数据进行存储;
-
返回存储的数组。
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']