Increment a string with letters?

MortenMoulder picture MortenMoulder · Jun 6, 2015 · Viewed 14.6k times · Source

I need to increment a string from.. let's say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go something like this:

aaa
aab
aac
...
aaz

aba
abb
abc
...
abz

aca
acb

And so on. So far I have incremented a single letter by doing this:

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

string = "aaa";

string = string.replaceAt(2, String.fromCharCode(string.charCodeAt(2) + 1));

//string == "aab"

However, I am lost when it comes to the final letter being z and it should then increment letter 2 (index 1) and reset the last letter to be a.

Does anyone have or know a smart solution to this? Thanks!

Answer

Rick Hitchcock picture Rick Hitchcock · Jun 6, 2015

Treat the string like it's a base 36 number.

Convert it to decimal, add 1, convert back to base 36, and replace any zeroes with the letter 'a':

var str= 'aaa',
    s= str;

while(str!=='zzz') {
  str= ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'a');
  s+= ' '+str;
}

document.body.innerHTML= s;