Javascript 什么是可以用来增加字母的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12504042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a method that can be used to increment letters?
提问by andyzinsser
Does anyone know of a Javascript library (e.g. underscore, jQuery, MooTools, etc.) that offers a method of incrementing a letter?
有谁知道提供增加字母的方法的 Javascript 库(例如下划线、jQuery、MooTools 等)?
I would like to be able to do something like:
我希望能够执行以下操作:
"a"++; // would return "b"
回答by Nathan Wall
Simple, direct solution
简单直接的解决方案
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
As others have noted, the drawback is it may not handle cases like the letter 'z' as expected. But it depends on what you want out of it. The solution above will return '{' for the character after 'z', and this is the character after 'z' in ASCII, so it could be the result you're looking for depending on what your use case is.
正如其他人所指出的,缺点是它可能无法按预期处理字母 'z' 之类的情况。但这取决于你想从中得到什么。上面的解决方案将为'z'之后的字符返回'{',这是ASCII中'z'之后的字符,因此它可能是您正在寻找的结果,具体取决于您的用例是什么。
Unique string generator
独特的字符串生成器
(Updated 2019/05/09)
(更新于 2019/05/09)
Since this answer has received so much visibility I've decided to expand it a bit beyond the scope of the original question to potentially help people who are stumbling on this from Google.
由于这个答案获得了如此多的关注,我决定将其扩展到原始问题的范围之外,以可能帮助那些在谷歌上绊倒的人。
I find that what I often want is something that will generate sequential, unique strings in a certain character set (such as only using letters), so I've updated this answer to include a class that will do that here:
我发现我经常想要的是在某个字符集中生成连续的、唯一的字符串的东西(例如只使用字母),所以我更新了这个答案以包含一个可以在此处执行此操作的类:
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();
}
}
}
Usage:
用法:
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'
回答by Zar
Plain javascript should do the trick:
普通的 javascript 应该可以解决问题:
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
回答by Ronnie Royston
What if the given letter is z? Here is a better solution. It goes A,B,C... X,Y,Z,AA,AB,... etc. Basically it increments letters like the column ID's of an Excel spreadsheet.
如果给定的字母是 z 呢?这是一个更好的解决方案。它是 A、B、C... X、Y、Z、AA、AB 等。基本上它会增加字母,如 Excel 电子表格的列 ID。
nextChar('yz'); // returns "ZA"
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>
回答by Sushanth --
You can try this
你可以试试这个
console.log( 'a'.charCodeAt?(0))?
First convert it to Ascii number .. Increment it .. then convert from Ascii to char..
首先将其转换为 Ascii 数字 .. 增加它 .. 然后从 Ascii 转换为字符 ..
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
var curr = String.fromCharCode(nex++)
console.log(curr)
});
?Check FIDDLE
?检查小提琴
回答by letiagoalves
I needed to use sequences of letters multiple times and so I made this function based on this SO question. I hope this can help others.
我需要多次使用字母序列,所以我根据这个 SO 问题制作了这个功能。我希望这可以帮助其他人。
function charLoop(from, to, callback)
{
var i = from.charCodeAt(0);
var to = to.charCodeAt(0);
for(;i<=to;i++) callback(String.fromCharCode(i));
}
- from -start letter
- to -last letter
- callback(letter) -function to execute for each letter in the sequence
- 从 -开始信
- 至 -最后一封信
- callback(letter) -为序列中的每个字母执行的函数
How to use it:
如何使用它:
charLoop("A", "K", function(char) {
//char is one letter of the sequence
});
回答by Sandeep Singh
One possible way could be as defined below
一种可能的方式如下定义
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 ...
回答by PitaJ
Adding upon all these answers:
添加所有这些答案:
// 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);
}
Example: http://jsfiddle.net/pitaj/3F5Qt/
回答by NikK
This one does work well:
这个效果很好:
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'
回答by dean schmid
A just for laughs solution
一个只是为了笑的解决方案
function nextLetter(str) {
const Alphabet = [
// lower case alphabet
"a", "b", "c",
"d", "e", "f",
"g", "h", "i",
"j", "k", "l",
"m", "n", "o",
"p", "q", "r",
"s", "t", "u",
"v", "w", "x",
"y", "z",
// upper case alphabet
"A", "B", "C",
"D", "E", "F",
"G", "H", "I",
"J", "K", "L",
"M", "N", "O",
"P", "Q", "R",
"S", "T", "U",
"V", "W", "X",
"Y", "Z"
];
const LetterArray = str.split("").map(letter => {
if (Alphabet.includes(letter) === true) {
return Alphabet[Alphabet.indexOf(letter) + 1];
} else {
return " ";
}
});
const Assemble = () => LetterArray.join("").trim();
return Assemble();
}
console.log(nextLetter("hello*3"));
回答by Stephen Quan
Here is a variation of the rot13 algorithm I submitted on https://stackoverflow.com/a/28490254/881441:
这是我在https://stackoverflow.com/a/28490254/881441 上提交的 rot13 算法的变体:
function rot1(s) {
return s.replace(/[A-Z]/gi, c =>
"BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"[
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
}
The input code in the bottom and the looked up codec is on the top (i.e. the output code is the same as the input code but shifted by 1). The function only changes letters, i.e. if any other character is passed in, it will be unchanged by this codec.
底部的输入代码和查找的编解码器在顶部(即输出代码与输入代码相同,但移动了 1)。该函数仅更改字母,即如果传入任何其他字符,则该编解码器不会对其进行更改。