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

1

2 Answers 2

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

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

Comments

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.

1 Comment

If this answer helped you solve your problem please mark it as the answer to your question.

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.