增量字符串数javascript

时间:2014-04-30 00:54:34

标签: javascript

抱歉这个noob问题,但我真的不善于使用javascript。我有一个字符串列表,其末尾有数字:

  1. Test-001
  2. 测试-002
  3. 测试-003
  4. 我想增加字符串末尾的数字。

    到目前为止我尝试了什么:

    var test = 'Test-001';
    var lastNum = test.split('-');
    
    console.log( lastNum[1] + 1 ); // result: 0011
    console.log( Number( lastNum[1] ) + 1 ) // result: 2
    

    我想要做的是产生结果(Test-001直到Test-999)。

    提前谢谢

2 个答案:

答案 0 :(得分:1)

你很接近....但试试这个:

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

答案 1 :(得分:0)

尝试做这样的事情:

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

这会对你有帮助。