简体   繁体   中英

Regular expression replace only one number into string

I have a code:

var locals = ["PontoRoteiro[0].LocalRoteiro[1]","PontoRoteiro[0].LocalRoteiro[3]","PontoRoteiro[0].LocalRoteiro[4]","PontoRoteiro[0].LocalRoteiro[5]"];
var result = [];

for(var i = 0; i < locals.length; i++)
{
  var l = locals[i];
  l = l.replace("^PontoRoteiro[0].LocalRoteiro[[0-9]*$]","PontoRoteiro[0].LocalRoteiro[" + i + "]"  )
  result.push(l);
}

console.log(result);

I need to sort the items, to stay in ascending order without skipping an index, how to replace the numbers that do not respect the index is?

[ and . are special characters, you have to escape them:

l = l.replace(/^PontoRoteiro\[0\]\.LocalRoteiro\[\d+\]/,"PontoRoteiro[0].LocalRoteiro["+i+"]")

You can simplify:

l = l.replace(/LocalRoteiro\[\d+\]/,"LocalRoteiro["+i+"]")

You are missing escapes on the . [ ] characters:

var locals = ["PontoRoteiro[0].LocalRoteiro[1]","PontoRoteiro[0].LocalRoteiro[3]","PontoRoteiro[0].LocalRoteiro[4]","PontoRoteiro[0].LocalRoteiro[5]"];
        var result = [];
        var regex, i, l;
        for(i = 0; i < locals.length; i++)
        {
            l = locals[i];
            regex = /^PontoRoteiro\[0\]\.LocalRoteiro\[[0-9]+\]/;
            l = l.replace(regex,"PontoRoteiro[0].LocalRoteiro[" + i + "]");
            result.push(l);
        }

        console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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