Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rionmonster/1babe751781a478146f63431af31f32c to your computer and use it in GitHub Desktop.
Save rionmonster/1babe751781a478146f63431af31f32c to your computer and use it in GitHub Desktop.
// This accepts a string numbuer and will increment the numeric part by 1
function stringNumber(str){
// This will use a regular expression to match the last series of numbers that appear in
// your string (/\d+$/) and it will map that value to a function that will replace it with
// the result of the actual number it contains (Number(n)), which will do something like
// mapping "999" to 999 and then incrementing it by 1 (Number(n) + 1)
return str.replace(/\d+$/, function(n) { return Number(n) + 1; });
}
function stringNumber(str){
// This essentially does the same thing as the previous version, except it can handle empty strings as
// well by just appending a 1. Basically it tests if the string ends with a digit (/\d+$/.test(str)),
// if this is true, it will use the first clause of the inline if-statement (code between ? and :), which
// performs the replacement you saw earlier. Otherwise, it will perform the second set (code after :, i.e.
// str + '1', which will simply add '1' to the end of your string
return /\d+$/.test(str) ? str.replace(/\d+$/, function(n) { return Number(n) + 1; }) : str + '1';
}
// The pad function will accept a number and a specific size to pad by (i.e the overall length of the result
function pad(num, size) {
// Firstly, you build a large string by concatenating a series of zeroes (enough to handle the largest values
// you would need, with your number. You then would take a substring from the end of this to build your result
// string (so if you had "0001" and used "0001".substr(-2), it would pull off the last two digits, yielding
// "01"
return ('0000000000' + num).substr(-size);
}
// This function puts everythign that you saw earlier together
function stringNumber(str) {
// This will perform your replacement as mentioned earlier or simply append a '1' at the end of your string
return /\d/.test(str) ? str.replace(/\d+$/, function(n) {
// Since it's possilbe that the end of the number might change, you need to account for that when padding.
// If you had 999, which is 3 characters long but were incrementing it, it would be 4 characters so we would
// need to handle that when padding (as otherwise we could get 000 instead of 1000)
var rangeToPad = /^9+$/.test(n) ? n.length + 1 : n.length;
// Pad our result by the specified amount
return pad(Number(n) + 1, rangeToPad);
})
// Or simply add a one to the value (padded by three digits)
: str + pad(1, 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment