0

Sorry for this noob question but I'm really not good with javascript. I have list of String which has number at the end:

  1. Test-001
  2. Test-002
  3. Test-003

I want to increment the numbers at the end of the String.

What I tried so far:

var test = 'Test-001';
var lastNum = test.split('-');

console.log( lastNum[1] + 1 ); // result: 0011
console.log( Number( lastNum[1] ) + 1 ) // result: 2

What I want to do is to produce results ( Test-001 up to Test-999 ).

Thank you in advance

3

2 Answers 2

1

You're close .... but try this on:

var test = 'Test-001';
var pieces = test.split('-');
var prefix = pieces[0];
var lastNum = pieces[1];
// lastNum is now a string -- lets turn it into a number. 
// (On older browsers, the radix 10 is essential -- otherwise it
// will try to parse the number as octal due to the leading zero.
// the radix is always safe to use and avoids any confusion.)

lastNum = parseInt(lastNum, 10);
// lastNum = +lastNum is also a valid option.

// Now, lets increment lastNum
lastNum++;

// Now, lets re-add the leading zeros
lastNum = ("0000" + lastNum).substr(-3);
Sign up to request clarification or add additional context in comments.

6 Comments

parseInt() will not work because it needs to begin with a number. Your lastNum is NaN.
@RUJordan Oops.. Fixed -- Thanks. Ran that through my console and it worked properly now.
This is not valid if the lastNum is Test-010 right?
@newbie -- Copy the code and run it in your own browser's console. If you set test to "Test-010" then lastNum will correctly equal 011 at the end.
("0000" + code).substr(-3) can you explain the logic of this a bit? How come its result is still right even I the input is Test-010?
|
0

Try to do something like this:

  var test = 'Test-001';
        var lastNum = test.split('-');
        var result=parseInt(lastNum[1]) + 1;
        console.log(parseInt(result, 10) < 100 ? ((parseInt(result, 10) < 10 ? ("00" + result) : ("0" + result))) : result);

        test = 'Test-009';
        lastNum = test.split('-');
        result = parseInt(lastNum[1]) + 1;
        console.log(parseInt(result, 10) < 100 ? ((parseInt(result, 10) < 10 ? ("00" + result) : ("0" + result))) : result);

        test = 'Test-099';
        lastNum = test.split('-');
        result = parseInt(lastNum[1]) + 1;
        console.log(parseInt(result, 10) < 100 ? ((parseInt(result, 10) < 10 ? ("00" + result) : ("0" + result))) : result);

This will help you.

1 Comment

Thanks for you suggestion but @jeremy's answer is much more simple.

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.