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.
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
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.