3

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.

7 Answers 7

4

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);

Sign up to request clarification or add additional context in comments.

Comments

3

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);

3 Comments

This answer is perfect, other answers can break for some of strings, Thank you Sinha!
If you start with "MPG_0099" then you end up with "MPG_00100" so I wouldn't say this is correct. You should end up with "MPG_0100"
@FrodmanG, yes you are correct. But that was the requirement in the original question.
2

Using regex along with the function padStart

function add(str, n) {
  return str.replace(/(\d+)/, function(match) {
    var length = match.length;
    var newValue = Number(match) + n;

    return newValue.toString(10).padStart(length, "0");
  });
}

console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));

3 Comments

MPG_0099 returns MPG_00100.. should probably return MPG_0100
yeah, i did see it, just thought it was a good answer and you might wanna fix it instead of just adding a note that your solution is broken. "MPG_0099".replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4)); is what i would've done but since you changed your answer entirely now i'll just add that to my answer.
@Occam'sRazor you're right, and cause that I've updated tha answer!
1

Using regular expression you can do it like this.

var text1 = 'MPG_0023';
var text2 = 'MPG_23';

var regex = /(.*_[0]*)(\d*)/;

var match1 = regex.exec(text1);
var match2 = regex.exec(text2);

var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);

console.log(newText1);
console.log(newText2);

Comments

0

Increment and pad the same value (comments inline)

var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";

console.log("currentValue ", value);

//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);

//method to get next value
var fnGetNextCounterValue = (value) => {
   var num = value.substring(prefix.length); //extract num value
   ++num; //increment value
   return prefix + fnPad(num, padDigit); //prepend prefix after padding
};

console.log( "Next",  value = fnGetNextCounterValue(value) );
console.log( "Next",  value = fnGetNextCounterValue(value) );
console.log( "Next",  value = fnGetNextCounterValue(value) );

Comments

0

One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.

var testString = "MGP_0023";
var ary = testString.split("_");

var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);

// helper function to add zeros in front of the number
function pad(number) {
    var str = number.toString();
    while (str.length < 4) {
        str = '0' + str;
    }

    return str;
}

Comments

0

You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.

Snippet below:

let str = "MPG_0023",
    num = Number(str.substr(4)) + 1,
    newStr = String(num);

function addLeading0(str) {
  return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}

console.log("MPG_" + addLeading0(newStr));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.