0

How to use zero padding in string which is combined with another character? I search for some example but they just show me string in number format.

For Example :

"000001" //Only number withount any character

I need zero padding for combined character

For example :

ABC000001 //This is inital value

Then I do a operation to incrase the initial value. So it will be :

ABC000002

But when I reach "ABC000009". The result must be "ABC000010".

Any answer would be appreciated

Rama Widi
  • 53
  • 1
  • 1
  • 10
  • Possible duplicate of [How can I pad a value with leading zeros?](https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros) – coudy.one Jun 05 '18 at 11:54

2 Answers2

2

You could

  • separate the string in some characters and digits at the right side,
  • add a value,
  • pad the string and
  • return a new string with all parts.

function add(string, value) {
    var [c, d] = string.match(/^(.*?)(\d+)$/).slice(1);
    
    return c + (+d + value).toString().padStart(d.length, '0');
}

console.log(add('ABC000001', 1));
console.log(add('A0BC00001', 1));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
let current = Number('ABC000001'.substring(3));
current++;
let zeroString = 'ABC00000';
zeroString.substring(0, 8 - current.toString().length) + current;
  • First line gets the current number by removing leading string,
  • Second line increments it,
  • Third has declaration of wanted string format,
  • Forth line is creating a new string in required format.