Increment a string with letters?

前端 未结 12 1287
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

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

12条回答
  •  野的像风
    2021-02-08 13:07

    The example below can work from a...a to z...z.

    String.prototype.replaceAt = function(index, character) {
      return this.substr(0, index) + character + this.substr(index + character.length);
    }
    
    String.prototype.inc = function() {
      var stop = 'z';
      var start = 'a';
      var currentIndex = this.length - 1;
      var string = this.replaceAt(currentIndex, String.fromCharCode(this.charCodeAt(currentIndex) + 1));
    
      for (var i = string.length - 1; i > 0; i--) {
        if (string[i] == String.fromCharCode(stop.charCodeAt(0) + 1)) {
          string = string.replaceAt(i - 1, String.fromCharCode(string.charCodeAt(i - 1) + 1));
          string = string.replaceAt(i, String.fromCharCode(start.charCodeAt(0)));
        }
      }
      return string;
    }
    
    var string = "aaa";
    var allStrings = string;
    while(string != "zzz") {
      string = string.inc();
      allStrings += " " + string;
    }
    document.getElementById("current").innerHTML = allStrings;

提交回复
热议问题