Concatenating Strings vs. Incrementing Numbers
If you want to actually increment your number, you'll have to make it an actual numeric value to begin with (as otherwise you would just be concatenating your two strings).
Consider just parsing the numeric part of your string via the Number()
function and then incrementing it within a replace()
call :
function stringNumber(str){
// Replace the number at the end of the string
return str.replace(/\d+$/, function(n) { return Number(n) + 1; });
}
If you want to extend this to handle scenarios where your string didn't contain a number, you could accomplish this fairly easily as well :
function stringNumber(str){
// Replace the number at the end of the string or append a 1 if no number
// was found
return /\d+$/.test(str) ? str.replace(/\d+$/, function(n) { return Number(n) + 1; }) : str + '1';
}
Example
function stringNumber(str) {
// Replace the number at the end of the string
return str.replace(/\d+$/, function(n) { return Number(n) + 1; });
}
console.log(stringNumber('hello999'));
Update: Now with Padding Strings
Since it sounds like you need to handle padded strings, you could do this through a simple padding function and by checking some edge cases to determine when you need to pad an extra digit :
function stringNumber(str) {
// Replace the number at the end of the string or add a padded version of your number
return /\d+$/.test(str) ? str.replace(/\d+$/, function(n) {
// Determine if we are looking at an edge (i.e. all 9s)
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);
}
function pad(num, size) {
return ('00000' + num).substr(-size);
}
Padding Example
function stringNumber(str) {
// Replace the number at the end of the string or add a padded version of your number
return /\d/.test(str) ? str.replace(/\d+$/, function(n) {
// Determine if we are looking at an edge (i.e. all 9s)
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);
}
function pad(num, size) {
return ('00000' + num).substr(-size);
}
console.log('hello => ' + stringNumber('hello'));
console.log('hello001 => ' + stringNumber('hello001'));
console.log('hello998 => ' + stringNumber('hello998'));
console.log('hello999 => ' + stringNumber('hello999'));