有没有人知道一个JavaScript库(如underscore、jQuery、MooTools等)可以提供递增字母的方法?
我想要做类似这样的事情:
"a"++; // would return "b"
有没有人知道一个JavaScript库(如underscore、jQuery、MooTools等)可以提供递增字母的方法?
我想要做类似这样的事情:
"a"++; // would return "b"
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
正如其他人所指出的那样,缺点是它可能无法像预期的那样处理字母'z'这种情况。但这取决于你想要什么。上面的解决方案将为'z'后面的字符返回'{',而这是ASCII码中'z'后面的字符,因此根据你的用例,这可能是你要寻找的结果。
(更新于2019/05/09)
由于这个答案获得了很高的关注度,我决定将其扩展到原始问题的范围之外,以帮助那些通过Google搜索到这个问题的人。
我发现我经常需要的是能够在某个字符集(比如只使用字母)中生成连续唯一字符串的东西,因此我更新了这个答案,包括一个可以实现这一点的类:
class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}
next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}
_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}
*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}
用法:
const ids = new StringIdGenerator();
ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'
// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'
// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'
原生JavaScript就可以解决问题:
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
如果给定的字母是z,那该怎么办呢? 这里有一个更好的解决方案。 它按照A、B、C...X、Y、Z、AA、AB等列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>
if (same(u,'Z')){
改为 if (u == 'Z'){
,现在完美运行了,谢谢! - Sean Kendletitled same(str,char)
没有粘贴进去?我不知道。 - Ronnie Roystonsame()
显然是一个自定义函数。嗯,==
可以用,如果我想更加确定,可以使用 ===
,但是我已经测试过了,没问题。再次感谢! - Sean Kendle一个可能的方法可以如下所定义
function incrementString(value) {
let carry = 1;
let res = '';
for (let i = value.length - 1; i >= 0; i--) {
let char = value.toUpperCase().charCodeAt(i);
char += carry;
if (char > 90) {
char = 65;
carry = 1;
} else {
carry = 0;
}
res = String.fromCharCode(char) + res;
if (!carry) {
res = value.substring(0, i) + res;
break;
}
}
if (carry) {
res = 'A' + res;
}
return res;
}
console.info(incrementString('AAA')); // will print AAB
console.info(incrementString('AZA')); // will print AZB
console.info(incrementString('AZ')); // will print BA
console.info(incrementString('AZZ')); // will print BAA
console.info(incrementString('ABZZ')); // will print ACAA
console.info(incrementString('BA')); // will print BB
console.info(incrementString('BAB')); // will print BAC
// ... and so on ...
你可以尝试这个。
console.log( 'a'.charCodeAt(0))
首先将其转换为Ascii数字...增加它...然后从Ascii转换为char。
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
var curr = String.fromCharCode(nex++)
console.log(curr)
});
Check 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);
}
我需要多次使用字母序列,所以我根据这个SO问题制作了这个函数。我希望这可以帮助其他人。
function charLoop(from, to, callback)
{
var i = from.charCodeAt(0);
var to = to.charCodeAt(0);
for(;i<=to;i++) callback(String.fromCharCode(i));
}
如何使用它:
charLoop("A", "K", function(char) {
//char is one letter of the sequence
});
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'
这是我的Javascript函数,用于获取无限的增量字母(仅限大写字母)
function getNextStringId(str) {
let index = str.length-1;
let baseCode= str.charCodeAt(index);
do{
baseCode= str.charCodeAt(index);
let strArr= str.split("");
if(strArr[index] == "Z"){
strArr[index] = "A";
if(index==0){
strArr.unshift("A");
}
}
else{
strArr[index]= String.fromCharCode(baseCode + 1);
}
str= strArr.join("");
index--;
} while(baseCode == 90)
return str;
}
getNextStringId("A") // B
getNextStringId("Z") // AA
getNextStringId("ABZZ") // ACAA
这真的很老了。但我需要这个功能,而且没有一个解决方案对我的用例最优。我想生成a、b、c...z、aa、ab...zz、aaa...。这个简单的递归可以完成任务。
function nextChar(str) {
if (str.length == 0) {
return 'a';
}
var charA = str.split('');
if (charA[charA.length - 1] === 'z') {
return nextID(str.substring(0, charA.length - 1)) + 'a';
} else {
return str.substring(0, charA.length - 1) +
String.fromCharCode(charA[charA.length - 1].charCodeAt(0) + 1);
}
};