Aman Deep Aman Deep - 1 month ago 7
Javascript Question

replace number at the end of url with incremented value

I need to match and replace the number at the end of the url with an incremented value.

url = "http://127.0.0.1:8000/hello/abc/14/"


output

result = "http://127.0.0.1:8000/hello/abc/15/"


I know there are many similar questions like this on stackoverflow but none of them worked for me as they had digits only once in the string while in my case its present multiple times throughout the string.

I tried this

newUrl = existingUrl.replace(/abc\/[0-9]+/g, function(match, number) {
return parseInt(number)+1;
});

Answer

Try this :

var result = url.replace(/(\d+)\/$/, function(x){ return parseInt(x, 10) + 1 + '/' })

or with :

var result = url.replace(/(\d+)\/$/, x => parseInt(x) + 1 + '/' )