newbie
newbie

Reputation: 1980

Increment String number javascript

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

Upvotes: 0

Views: 3288

Answers (2)

Naveen Chandra Tiwari
Naveen Chandra Tiwari

Reputation: 5123

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.

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

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

Upvotes: 1

Related Questions