Increment the numeric part of a string

When you have a string that ends with a number, this simple regular expression will allow you to increment the number part e.g. take a text field containing "abc15" and increment it by 1 to return "abc16". Similarly, "xyz99" will become "xyz100", etc.

by David Waterston

HTML

<div id="output"></div>

JavaScript

function incrementString(str) {
    
    return str.replace(/\d+$/, function(n) { return ++n });

}

var o = document.getElementById('output');


// The following show the kind of data this is intended to be used on

o.innerHTML += '1. "abc15" --> "' + incrementString('abc15') + '"<br>';

o.innerHTML += '2. "xyz99" --> "' + incrementString('xyz99') + '"<br>';

o.innerHTML += '3. "127" --> "' + incrementString('127') + '"<br>';

o.innerHTML += '4. "abc-1" --> "' + incrementString('abc-1') + '"<br>';

o.innerHTML += '5. "-1" --> "' + incrementString('-2') + '"<br>';


// Of course, you can also use the replace inline, no need for a function
o.innerHTML += '6. "abc15" --> "' + 'abc15'.replace(/\d+$/, function(n) { return ++n }) + '"<br>';


// The following show the kind of data this is *not* intended to be used on

o.innerHTML += '7. "abc15a" --> "' + incrementString('abc15a') + '"<br>'; // Does nothing

o.innerHTML += '8. "abc" --> "' + incrementString('abc') + '"<br>'; // Does nothing