Created
January 8, 2015 18:34
-
-
Save jqn/27280c2eb184a3729d6b to your computer and use it in GitHub Desktop.
JS String Incrementer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) { | |
if(isNaN(parseInt(input[input.length - 1]))) return input + '1'; | |
return input.replace(/(0*)([0-9]+$)/, function(match, p1, p2) { | |
var up = parseInt(p2) + 1; | |
return up.toString().length > p2.length ? p1.slice(0, -1) + up : p1 + up; | |
}); | |
} | |
console.log(incrementString("foo"));//should log foo1 | |
console.log(incrementString("foobar23"));//should log foobar24 | |
console.log(incrementString("foo0042"));//should log foo0043 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment