javascriptphpexcelfor-loop

Javascript Algorithm to get the excel-like column name


Basically what I want to do is create list of characters with format like excel column name.

for example : a,b,c,d,.....,z,aa,ab,ac,....,yz

in php you can just looping it with this code:

for($char = "A"; $char <= "Z"; $char++) 
{
    echo $char . "\n";
}

but when I try it in javascript :

 var i3;
 var text3 = "";

for(i3 = "A"; i3 <= "Z"; i3++)
{
    text3 += i3 + ", ";
}

document.getElementById("pId").innerHTML = text3;

It doesn't work for me. Are there some errors in my code? Or that PHP logic doesn't work in JS? If you know how to make one please tell me, thanks.


Solution

  • In javacript the incrementor operator will return NaN when called on a string value.

    You can use ascii code based implementation like

    var i3, i4;
    var text3 = "";
    
    for (i3 = 0; i3 < 26; i3++) {
      text3 += String.fromCharCode(97 + i3) + ", ";
    }
    for (i3 = 0; i3 < 26; i3++) {
      for (i4 = 0; i4 < 26; i4++) {
        text3 += String.fromCharCode(97 + i3) + String.fromCharCode(97 + i4) + ", ";
      }
    }
    
    
    document.getElementById("pId").innerHTML = text3;
    <span id="pId"></span>