【问题标题】:Replace array like string to array with character replace用字符替换将数组(如字符串)替换为数组
【发布时间】:2013-11-08 04:39:34
【问题描述】:

我有一个这样的字符串"12,a,{3,4},b,c",我需要将它转换成一个数组,其中花括号中的元素应该是一个子数组,结果应该是这样的

["12","a",[3,4],"b","c"]

其他如:

"12,a,b,c,{e,f}" --> ["12","a","b","c", ["e","f"]]

"{12,a},b,c,{c,d}" --> [["12","a"],"b","c", ["e","f"]]

【问题讨论】:

  • 这样的数组可以接受吗? [["12"],["a"],["3","4"],["b"],["c"]] 这可以表示为一个锯齿状的字符串数组。
  • 应该是,但最后
  • 你这样做是为了什么?

标签: javascript regex arrays string replace


【解决方案1】:
var a = "12,a,{3,4},b,c,{2,3}";
var b = eval(("[" + a.replace(/{/g, '[').replace(/}/g, ']') + "]").replace(/[a-zA-Z]/g, function (all, match) { return "'" + all+ "'";}));
console.log(b)

试试这个

【讨论】:

  • b 是字符串,我想要 b 作为数组
  • a = "12,'a',{3,4},'b','c',{2,3}";不可能它的 "12,a,{3,4},b,c,{2,3}"
  • @rab 请解释为什么 eval 是个坏主意?
  • @Sarath Saleem 请检查您是否得到了所需的答案
【解决方案2】:

你可以试试这个代码:

a = "{12,a},b,c,{c,d}";
m = a.match(/{[^}]*}|[^,]+/g);
arr=[];

for (i=0; i<m.length; i++) {
    if (m[i].indexOf('{') >= 0)
        arr.push(m[i].replace(/[{}]/g, "").split(/,/));
    else
    arr.push(m[i]);
}
console.log(arr);

输出:

[[12,a],b,c,[c,d]]

【讨论】:

    【解决方案3】:

    你能试试这个吗?

    var m = "{12,a},b,c,{c,d}".split(','),
    
    result = m.reduce( function( a, b) {
    
        if ( b.indexOf('{') !== -1 || a.t.length ){
            a.t.push( b.replace(/\{|\}/,'') );
        } else {
            a.array.push( b );
        }
    
        if ( b.indexOf('}') !== -1 ){
            a.array.push( a.t );
            a.t = [];
        }
        return a ;
    
    }, { array:[],t:[]} ).array;
    
    console.log( result );
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2012-04-26
      • 2018-09-15
      • 2019-02-26
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多