解析这个字符串的最佳方法是什么?

时间:2015-09-04 10:36:25

标签: javascript string split

我有这个JavaScript字符串:

var str = "ct [b r 0 0 100 100] b r 0 0 1000 1000 c f red";

想得到这样的数组:

['ct', ['b', 'r', 0, 0, 100, 100], 'b', 'r', 0, 0, 1000, 1000, 'c', 'f', 'red'];

在原始字符串中,字母代表要采取的动作,数字代表坐标,并且那里也有嵌套数组(第二项)。

我想问的问题是:当一些项目本身可能包含(非转义)空格时,如何在空格上拆分字符串?

3 个答案:

答案 0 :(得分:0)

我可能会尝试这样的事情:

var str = "ct [b r 0 0 100 100] b r 0 0 1000 1000 c f red";

// the regex picks up the first 'element' (ct), the inner array
// and all the rest
var regex = /(.*)\[(.*)\](.*)/;
var match = str.match(regex)

// take the first 'element', and add it to the rest - 
// create an array
var init = (match[1].trim() + match[3]).split(' ');

// pass it through the checkNum function
// init is an array that has strings and integers
init = checkNum(init);

// grab the inner array and run it through checkNum
var inner = checkNum(match[2].split(' '));

// splice the inner array into the main array
init.splice(1, 0, inner);

function checkNum(arr) {

    // for each element in the array, if it's conversation
    // to an integer results in NaN, return the element, otherwise
    // return the integer
    for (var i = 0, l = arr.length; i < l; i++) {
        arr[i] = isNaN(+arr[i]) ? arr[i] : +arr[i];
    }
    return arr;
}

输出

['ct', ['b', 'r', 0, 0, 100, 100], 'b', 'r', 0, 0, 1000, 1000, 'c', 'f', 'red'];

DEMO

答案 1 :(得分:0)

jsfiddle:https://jsfiddle.net/e1xhq39w/

var str = "ct [b r 0 0 100 100] b r 0 0 1000 1000 c f red";
var strArr = str.split(' ');
console.log(JSON.stringify(parseArray(strArr)));


function parseArray(strArr) {
    var finalArray = [];
    var tempArray = [];
    var start = -1;
    var end = -1;
    for(var i=0;i<strArr.length;i++) {
        //skip array to a temp
        if(strArr[i].indexOf('[') != -1) {
            start = i;
            tempArray.push(strArr[i].replace('[', ''));
            continue;
        }
        if(strArr[i].indexOf(']') != -1) {
            end = i;
            start = -1;
            tempArray.push(strArr[i].replace(']', ''));
            finalArray.push(parseArray(tempArray));
            continue;
        }
        if(start != -1) {
            tempArray.push(strArr[i]);
            continue;
        }
        var number = Number(strArr[i]);
        if(isNaN(number)) {         
            finalArray.push(strArr[i])
           }
        else {
            finalArray.push(number);
        }   
    }
    return finalArray;
}

答案 2 :(得分:-2)

首先,您必须查看输入数据并确定用于将数据拆分为单个数组实体的标准。在这里,它将是''

JavaScript有一个名为split的内置函数,它将字符串拆分成一个数组,你所要做的就是提供程序应该查找的字符,当它找到这个字符时,程序会将数组拆分为那一点

var str = "ct [b r 0 0 100 100] b r 0 0 1000 1000 c f red";
var array = str.split(" "); //this will now store the str split into an array

数组应该等于:

ct, [b, r, 0, 0, 100, 100], b, r, 0, 0, 1000, 1000, c, f, red

对于[],我不确定