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 s
I just want to provide an alternative answer to @procrastinator's (since I can't comment on the answer because I don't have enough points on Stackoverflow). His answer seems like the most generic approach but I can't help and notice that after "z" comes "ba" when op expect it to be "aa". Also, this follows how Excel name it's columns.
Here is the code with corrections:
function s2n(s) {
var pow, n = 0, i = 0;
while (i++ < s.length) {
pow = Math.pow(26, s.length - i);
var charCode = s.charCodeAt(i - 1) - 96;
n += charCode * pow;
}
return n;
}
function n2s(n) {
var s = '';
var reduce = false;
if (n === undefined) {
n = 0;
} else {
n--;
}
while (n !== undefined) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
if (n === 0) {
n = undefined;
} else {
n--;
}
}
return s;
}
Instead of starting from 0, this will consider 1 to be "a", 26 to be "z", 27 to be "aa" and so on.