Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you keep the leading zeros in a new Number() in JavaScript [duplicate]

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

like image 927
Daniel C Avatar asked Sep 05 '25 03:09

Daniel C


2 Answers

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));
like image 95
Nina Scholz Avatar answered Sep 07 '25 21:09

Nina Scholz


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

like image 24
Daniel C Avatar answered Sep 07 '25 20:09

Daniel C