您的位置:首页 > Web前端 > JavaScript

JavaScript:to write a function which increments a string, to create a new string

2015-04-23 14:55 691 查看
Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.

Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

Attention: If the number has leading zeros the amount of digits should be considered.

function incrementString(input) {
  // return incrementedString
  var inputLen = input.length;
  var lastELePos = inputLen-1;
  var lastEle = input.charAt(lastELePos);

  if (/\d/g.test(lastEle)) {  // /\d/g 判断是非为数值 如果是 则运行
       for(var i=0;i<inputLen;i++){
        //找第一个不0的数字的位置
        if(/\d/g.test(input.charAt(i)) && input.charAt(i)!=0 ){
                var s1 = input.substring(0,i);
                var s2 = Number(input.substring(i))+1;
                var newStr = s1+s2;
                return newStr;
            }
        }
    }else {
        var newStr = input + "1";
        return newStr;
    }
}

var s1 = incrementString('foobar');
var s2 = incrementString('foobar01');
var s3 = incrementString('foobar009');
alert(s1);  //foobar1
alert(s2);  //foobar02
alert(s3);  //foobar0010
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐