Search code examples
javascriptregexstringnumbersincrement

String increment: increment the last string by one


the purpose of this code is to 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. e.g. "foo123" --> "foo124" or "foo" --> "foo1". With my code below, pretty much all my test cases are passed except a corner case for "foo999" did not print out "foo1000". I know that there should be a way to do with regex to fix my problem, but I am not too familiar with it. Can anyone please help?

function incrementString (input) {
  var reg = /[0-9]/;
  var result = "";
  if(reg.test(input[input.length - 1]) === true){
    input = input.split("");
    for(var i = 0; i < input.length; i++){
        if(parseInt(input[i]) === NaN){
            result += input[i];
        }
        else if(i === input.length - 1){
            result += (parseInt(input[i]) + 1).toString();
        }
        else{
            result += input[i];
        }
    }
    return result;
  }
  else if (reg.test(input[input.length - 1]) === false){
    return input += 1;
  }
}


Solution

  • function pad(number, length, filler) {
        number = number + "";
        if (number.length < length) {
            for (var i = number.length; i < length; i += 1) {
                number = filler + number;
            }
        }
    
        return number;
    }
    
    function incrementString (input) {
        var orig = input.match(/\d+$/);
        if (orig.length === 1) {
            orig = pad(parseInt(orig[0]) + 1, orig[0].length, '0');
            input = input.replace(/\d+$/, orig);
            return input;
        }
    
        return input + "1";
    }
    

    What does it do?

    It first checks if there is a trailing number. If yes, increment it and pad left it with zeros (with the function "pad" which you'd be able to sort it out yourself).

    string.replace is a function which works with argument 1 the substring to search (string, regex), argument 2 the element to replace with (string, function).

    In this case I've used a regex as first argument and the incremented, padded number.

    The regex is pretty simple: \d means "integer" and + means "one or more of the preceeding", which means one or more digits. $ means the end of the string.

    More info about regular expressions (in JavaScript): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp (thanks @Casimir et Hippolyte for the link)