Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a string in JavaScript containing leading zeros?

Tags:

javascript

I have string like:

MPG_0023

I want to find something like

MPG_0023 + 1

and I should get

MPG_0024

How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.

There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.

like image 390
ace Avatar asked Apr 01 '26 09:04

ace


2 Answers

Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.

var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);

Or if you do wanna do regex, the underscore won't matter.

var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
like image 103
I wrestled a bear once. Avatar answered Apr 03 '26 22:04

I wrestled a bear once.


You can use the regular expressions to make the changes as shown in the following code

var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024

console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
like image 36
Sinha Avatar answered Apr 03 '26 23:04

Sinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!