什么是可以用来增加字母的方法?

有谁知道一个Javascript库(例如下划线,jQuery,MooTools等),提供了一个递增的方法字母?

我希望能够做到这样的事情:

"a"++; // would return "b" 
 function nextChar(c) { return String.fromCharCode(c.charCodeAt(0) + 1); } nextChar('a'); 

普通的JavaScript应该做的伎俩:

 String.fromCharCode('A'.charCodeAt() + 1) // Returns B 

如果给定的字母是z呢? 这是一个更好的解决scheme。 它是A,B,C … X,Y,Z,AA,AB等等。基本上,它像Excel电子表格的列ID一样递增字母。

nextChar( 'YZ'); //返回“ZA”

  function nextChar(c) { var u = c.toUpperCase(); if (same(u,'Z')){ var txt = ''; var i = u.length; while (i--) { txt += 'A'; } return (txt+'A'); } else { var p = ""; var q = ""; if(u.length > 1){ p = u.substring(0, u.length - 1); q = String.fromCharCode(p.slice(-1).charCodeAt(0)); } var l = u.slice(-1).charCodeAt(0); var z = nextLetter(l); if(z==='A'){ return p.slice(0,-1) + nextLetter(q.slice(-1).charCodeAt(0)) + z; } else { return p + z; } } } function nextLetter(l){ if(l<90){ return String.fromCharCode(l + 1); } else{ return 'A'; } } function same(str,char){ var i = str.length; while (i--) { if (str[i]!==char){ return false; } } return true; } // below is simply for the html sample interface and is unrelated to the javascript solution var btn = document.getElementById('btn'); var entry = document.getElementById('entry'); var node = document.createElement("div"); node.id = "node"; btn.addEventListener("click", function(){ node.innerHTML = ''; var textnode = document.createTextNode(nextChar(entry.value)); node.appendChild(textnode); document.body.appendChild(node); }); 
 <input id="entry" type="text"></input> <button id="btn">enter</button> 

我需要多次使用字母序列,所以我根据这个SO问题做了这个函数。 我希望这可以帮助别人。

 function charLoop(from, to, callback) { var i = from.charCodeAt(0); var to = to.charCodeAt(0); for(;i<=to;i++) callback(String.fromCharCode(i)); } 
  • 从 –开始信
  • 最后一封信
  • callback(字母) –执行序列中每个字母的函数

如何使用它:

 charLoop("A", "K", function(char) { //char is one letter of the sequence }); 

看到这个工作演示

你可以试试这个

 console.log( 'a'.charCodeAt​(0))​ 

首先将其转换为Ascii号..增量它..然后从Ascii转换为字符..

 var nex = 'a'.charCodeAt(0); console.log(nex) $('#btn1').on('click', function() { var curr = String.fromCharCode(nex++) console.log(curr) }); 

检查FIDDLE

加上所有这些答案:

 // first code on page String.prototype.nextChar = function(i) { var n = i | 1; return String.fromCharCode(this.charCodeAt(0) + n); } String.prototype.prevChar = function(i) { var n = i | 1; return String.fromCharCode(this.charCodeAt(0) - n); } 

例如: http : //jsfiddle.net/pitaj/3F5Qt/

这个很好用:

 var nextLetter = letter => { let charCode = letter.charCodeAt(0); let isCapital = letter == letter.toUpperCase(); if (isCapital == true) { return String.fromCharCode((charCode - 64) % 26 + 65) } else { return String.fromCharCode((charCode - 96) % 26 + 97) } } EXAMPLES nextLetter("a"); // returns 'b' nextLetter("z"); // returns 'a' nextLetter("A"); // returns 'B' nextLetter("Z"); // returns 'A' 
Interesting Posts