3

guys.

I'm having some issues with this function

const incrementString = str => {
  if (!str.match(/[\d+]$/)){
    return str += 1
  } else{
    return str.replace(/[\d+]$/, ch => new Number(ch) + 1)
  }
}

What I'm trying to do with that function is + 1 the number at the end of the string, and if the string doesn't has one, I'll add a 1 at the end.

string      expected
"foobar000" "foobar001"
"foo"       "foo1"
"foobar025" "foobar026"

I don't know if it's possible to do it with replace and regex, I have in mind a solution with loops, .length, split, etc..., but I want to do it with regex, if it's possible.

Problem: How can I take the number at the end of the string, with the leading zeros, and sum them a 1? this are some examples of the bad behavior of my function

Expected: 'foobar011', instead got: 'foobar11'
Test Passed: Value == 'foo1'
Expected: 'foobar002', instead got: 'foobar2'
Test Passed: Value == 'foobar100'
Test Passed: Value == 'foobar100'
Test Passed: Value == '1'

Thanks and happy holydays

Daniel C
  • 51
  • 1
  • 6

2 Answers2

7

You could store the length of the numerical string and apply after incrementing the wanted leading zeroes.

function increment(s) {
    var [left, right = '0'] = s.split(/(\d*$)/),
        length = right.length;

    return left + (+right + 1).toString().padStart(length, '0');
}

console.log(['foobar000', 'foo', 'foobar025'].map(increment));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • Is line 2 is creating to `var`s and assigning the value `s.split(/(\d*$)/)` to left and `'0'` to right? How is called this syntax? I've never seen it before. – Mattia Dec 28 '18 at 18:42
  • 2
    it's a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). – Nina Scholz Dec 28 '18 at 18:45
1

I used all your hints and answers to check different options to solve my problem.

Finally, I solved with the "String of numbers" and the padStart hints.

const incrementString = str => {
  if (str.match(/[0-9+]+/g)) {
    let numbers = str.replace(/[a-z+]+/g, "")
    return str.replace(numbers, (Number(numbers) + 1 + '').padStart(numbers.length, 0))
  } else {
    return str + 1
  }
}

I hope this helps others as it helped to me.

Thanks and happy holydays

Daniel C
  • 51
  • 1
  • 6