0

So the challenge is to increment a string and the exact rules are as follows:

  • If the string already ends with a number, the number should be incremented by 1.

  • If the string does not end with a number. the number 1 should be appended to the new string.

Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

I've gotten so close with two different attempts. Both check off certain boxes but neither do both.

function incrementString (strng) {
  if (/\d/.test(strng) === true) {
    var num = +strng.match(/\d+/g)[0] + 1;    
    return strng.replace(/[1-9]/g,'') + num;
  } else {
    return strng + "1";
  }
}

This returns the string, keeping the zeros ahead of the incremented number. However on a test like "foobar099" I need to return "foobar100" but get "foobar0100".

function incrementString (strng) {
  if (/\d/.test(strng) === true) {
    var num = +strng.match(/\d+/g)[0] + 1;    
    return strng.replace(/\d/g,'') + num;
  } else {
    return strng + "1";
  }
}

This is another close attempt that successfully increments tests like "foobar099" -> "foobar100" but abandons the zeros for tests such as "foobar0042" which becomes "foobar43".

Anyone able to solve this?

  • seperate the numbers and string and keep a check on their length , then once the number is incremented , append extra `0` at the end of the string along with the updated number –  Jul 27 '20 at 07:42

1 Answers1

1

Is this what you want?

function incrementString(text) {
    return text.replace(/(\d*)$/, (_, t) => (+t + 1).toString().padStart(t.length, 0));
}

console.log(incrementString('foo'));
console.log(incrementString('foobar23'));
console.log(incrementString('foo0042'));
console.log(incrementString('foo9'));
console.log(incrementString('foo099'));
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • I just started learning javascript..can you please explain what is this doing.`(_, t) => (+t + 1)` AFAIK this is a callback but can't understand what would be the value of arguments here. – greenlantern Feb 07 '22 at 05:52