简体   繁体   English

正则表达式和Javascript从字符串中删除数字

[英]Regex and Javascript to remove numbers from string

I have a string: 我有一个字符串:

 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
            },'

That I use this regex to add '_#' to elements that have ':{' at the end of them 我使用此正则表达式将'_#'添加到末尾带有':{'的元素

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

The ouput is 输出是

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
        },'

Then I do a bunch of stuff with it and now I need to strip out the ' #' from it. 然后,我用它做一堆东西,现在我需要从中去除“ #”。 How would I go about removing those ' #' 我将如何删除这些“ #”

Not cessary but another problem I am having is the the first regex is incrementing starting from 0 and giving each element the next incremented number. 不是必需的,但我遇到的另一个问题是第一个正则表达式从0开始递增,并为每个元素赋予下一个递增的数字。 I am trying to make it so that each element increments on its type. 我正在尝试使其每个元素在其类型上递增。 Like this: 像这样:

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
        },'

Any input on what im doing wrong here too? 我在这里做错什么的任何输入吗?

For the first question, just replace _\\d+:{ with :{ 对于第一个问题,只需将_\\d+:{替换为:{

For the second, you need a separate counter for each type. 对于第二种,每种类型都需要一个单独的计数器。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM