将字符串拆分为多组字符串

时间:2011-04-06 12:46:42

标签: javascript split

我有一个包含元素列表的字符串,其中一些是固定的,其中一些是可选的。举个例子,假设我的字符串是一个购物清单:

"strawberry, raspberry, $2{tomato, sauerkraut, beans},
 potato, $1{{apple, pear}, {orange, banana}}"

我想最终得到类似的东西:

["strawberry",
 "raspberry",
 [2, "tomato", "sauerkraut", "beans"],
 "potato",
 [1, ["apple", "pear"], ["orange", "banana"]]

我不知道如何解决这里的多种选择,所以我愿意接受任何建议。你也可以修改“语法”(例如"$[num of coices]{list}")并添加/删除绒毛,这并不重要。更加简单的行人! :

编辑:我有上述格式的这些列表,除非没有其他解决方案,否则不能手动转换它们:...(

谢谢!

2 个答案:

答案 0 :(得分:4)

为什么不使用JSON

var list = ["strawberry",
     "raspberry",
     [2, "tomato", "sauerkraut", "beans"],
     "potato",
     [1, ["apple", "pear"], ["orange", "banana"]]];

var str = JSON.stringify(list);
/*
str = '["strawberry","raspberry",[2,"tomato","sauerkraut","beans"],"potato",[1,["apple","pear"],["orange","banana"]]]'
*/

var list2 = JSON.parse(str);
/*
list2 = ["strawberry",
         "raspberry",
         [2,"tomato","sauerkraut","beans"],
         "potato",
         [1, ["apple","pear"], ["orange","banana"]]]
*/

答案 1 :(得分:1)

首先:我强烈建议使用Matt提到的基于 JSON 的解决方案。 但由于某种原因,你不能调整你当前的代码,然后试试这个: 注意:我没有针对不同的测试用例进行测试,但我认为它会给你一个想法......

  var testString = "strawberry, raspberry, $2{tomato, sauerkraut, beans},  potato, $1{{apple, pear}, {orange, banana}}";
    testString = testString.replace(/\$(\d+){/g, "{$1,");
    testString = testString.replace(/{/g, "[").replace(/}/g, "]");
    testString = testString.replace(/\b/g,'"')
    testString = testString.replace(/(")(\[)/g,'$2$1')
    testString = testString.replace(/(\])(")/g,'$2$1')
    testString = '[' + testString + ']';
    var obj = JSON.parse(testString);
    for(var o in obj)
    {
        alert(typeof obj[o]);
    }

工作示例:http://jsfiddle.net/PcMhw/4/