1

我有一个字符串:

 str =    'View:{
            Name:"View1",
            Image:{
                BackgroundImage:"Image.gif",
                Position: [0, 0],
                Width: 320,
                Height: 480
            },

            Button:{
                BackgroundImage:"Button.gif",
                Transition:"View2",
                Position: [49, 80],
                Width: 216,
                Height: 71
            },

            Button:{
                BackgroundImage:"Button2.gif",
                Position: [65, 217],
                Width: 188,
                Height: 134
            },'

我使用此正则表达式将 '_#' 添加到末尾有 ':{' 的元素

var i = 0;
str = str.replace(/([^:]+):{/g, function(m, p1) { return p1 + "_" + (++i).toString() + ":{"; });

输出是

str =    'View_1:{
        Name:"View1",
        Image_2:{
            BackgroundImage:"Image.gif",
            Position: [0, 0],
            Width: 320,
            Height: 480
        },

        Button_3:{
            BackgroundImage:"Button.gif",
            Transition:"View2",
            Position: [49, 80],
            Width: 216,
            Height: 71
        },

        Button_4:{
            BackgroundImage:"Button2.gif",
            Position: [65, 217],
            Width: 188,
            Height: 134
        },'

然后我用它做了一堆东西,现在我需要从中去掉' #'。我将如何删除那些' #'

没有必要,但我遇到的另一个问题是第一个正则表达式从 0 开始递增,并为每个元素提供下一个递增的数字。我正在尝试使每个元素在其类型上递增。像这样:

str =    'View_1:{
        Name:"View1",
        Image_1:{
            BackgroundImage:"Image.gif",
            Position: [0, 0],
            Width: 320,
            Height: 480
        },

        Button_1:{
            BackgroundImage:"Button.gif",
            Transition:"View2",
            Position: [49, 80],
            Width: 216,
            Height: 71
        },

        Button_2:{
            BackgroundImage:"Button2.gif",
            Position: [65, 217],
            Width: 188,
            Height: 134
        },'

关于我在这里做错了什么的任何意见?

4

1 回答 1

1

对于第一个问题,只需替换_\d+:{:{

其次,您需要为每种类型设置一个单独的计数器。尝试这个:

var i = {};
str = str.replace(/([^:]+):{/g, function(m, p1) {
    i[p1] = (i[p1] || 0)+1;
    return p1 + "_" + i[p1].toString() + ":{";
});
于 2012-12-28T19:03:40.850 回答