มีใครรู้จักไลบรารี Javascript (เช่นขีดล่าง, jQuery, MooTools ฯลฯ ) ที่เสนอวิธีการเพิ่มตัวอักษรหรือไม่?
ฉันต้องการที่จะทำสิ่งต่างๆเช่น:
"a"++; // would return "b"
มีใครรู้จักไลบรารี Javascript (เช่นขีดล่าง, jQuery, MooTools ฯลฯ ) ที่เสนอวิธีการเพิ่มตัวอักษรหรือไม่?
ฉันต้องการที่จะทำสิ่งต่างๆเช่น:
"a"++; // would return "b"
คำตอบ:
function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
ดังที่คนอื่น ๆ ตั้งข้อสังเกตข้อเสียคืออาจไม่สามารถจัดการกับกรณีเช่นตัวอักษร 'z' ได้ตามที่คาดไว้ แต่ขึ้นอยู่กับสิ่งที่คุณต้องการจากมัน วิธีแก้ปัญหาข้างต้นจะส่งคืน '{' สำหรับอักขระหลัง 'z' และนี่คืออักขระหลัง 'z' ใน ASCII ดังนั้นจึงอาจเป็นผลลัพธ์ที่คุณต้องการขึ้นอยู่กับกรณีการใช้งานของคุณ
(อัปเดต 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, ... ฯลฯ โดยทั่วไปจะเพิ่มตัวอักษรเช่นรหัสคอลัมน์ของสเปรดชีต Excel
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'){และทำงานได้อย่างสมบูรณ์ขอบคุณ!
                    same(str,char)ว่าไม่ได้วางไว้ในนั้น? ไม่รู้สินะ.
                    same()ชัดเจนเป็นฟังก์ชันที่กำหนดเอง โอ้==ใช้ได้ผลและถ้าฉันอยากจะมั่นใจสุด ๆ ฉันก็ใช้ได้===แต่ฉันได้ทดสอบแล้วก็ใช้ได้ ขอบคุณอีกครั้ง!
                    วิธีหนึ่งที่เป็นไปได้อาจเป็นไปตามที่กำหนดไว้ด้านล่าง
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 เป็นถ่าน ..
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
   var curr = String.fromCharCode(nex++)
   console.log(curr)
});
ตรวจสอบFIDDLE
ฉันจำเป็นต้องใช้ลำดับของตัวอักษรหลาย ๆ ครั้งดังนั้นฉันจึงสร้างฟังก์ชันนี้ตามคำถาม 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
});
เพิ่มคำตอบเหล่านี้ทั้งหมด:
// 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'
ทางออกสำหรับการหัวเราะ
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"));นี่มันเก่าจริงๆ แต่ฉันต้องการฟังก์ชันนี้และไม่มีวิธีแก้ปัญหาใดที่เหมาะสมกับกรณีการใช้งานของฉัน ฉันต้องการสร้าง 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);
}
};
สร้างฟังก์ชันด้วย {a: 'b', b: 'c', etc} ในการปิด: -
let nextChar = (s => (
    "abcdefghijklmopqrstuvwxyza".split('')
    .reduce((a,b)=> (s[a]=b, b)), // make the lookup
c=> s[c] // the function returned
))({}); // parameter s, starts empty
การใช้งาน: -
nextChar('a')
การเพิ่มตัวพิมพ์ใหญ่และตัวเลข: -
let nextCh = (
    (alphabeta, s) => (
        [alphabeta, alphabeta.toUpperCase(), "01234567890"]
            .forEach(chars => chars.split('')
               .reduce((a,b) => (s[a]=b, b))), 
        c=> s[c] 
    )
)("abcdefghijklmopqrstuvwxyza", {});
ps ใน Javascript บางเวอร์ชันคุณสามารถใช้[...chars]แทนไฟล์chars.split('')
นี่คือรูปแบบของอัลกอริทึม rot13 ที่ฉันส่งไปที่https://stackoverflow.com/a/28490254/881441 :
function rot1(s) {
  return s.replace(/[A-Z]/gi, c =>
    "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"[
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
}
รหัสอินพุตที่ด้านล่างและตัวแปลงสัญญาณที่ค้นหาจะอยู่ด้านบน (กล่าวคือรหัสเอาต์พุตจะเหมือนกับรหัสอินพุต แต่เลื่อนด้วย 1) ฟังก์ชันจะเปลี่ยนตัวอักษรเท่านั้นกล่าวคือหากมีการส่งผ่านอักขระอื่นใดตัวแปลงสัญญาณนี้จะไม่เปลี่ยนแปลง
function charLoop(from, to, callback) {
    var i = from.charCodeAt(0);
    var to = to.charCodeAt(0);
    for (; i <= to; i++) {
        callback(String.fromCharCode(i));
    }
}
var sequence = "";
charLoop("A", "Z", function (char) {
    sequence += char + " ";
});
sequence = sequence.trim();
sequence = sequence.split(" ");
var resseq = sequence;
var res = "";
var prevlet = "";
var nextlet = "";
for (b = 0; b < resseq.length; b++) {
    if (prevlet != "") {
        prevlet = resseq[b];
    }
    for (a = 0; a < sequence.length; a++) {
        for (j = 1; j < 100; j++) {
            if (prevlet == "") {
                prevlet = sequence[a];
                nextlet = sequence[a + 1];
                res += sequence[a] + sequence[a] + 0 + j + " ";
            }
            else {
                if (j < 10) {
                    res += prevlet + sequence[a] + 0 + j + " ";
                }
                else {
                    res += prevlet + sequence[a] + j + " ";
                }
            }
        }
    }
}
document.body.innerHTML = res;
ขึ้นอยู่กับการเพิ่มและลดคำตอบของ @Nathan wall
// Albhabet auto increment and decrement
class StringIdGenerator {
    constructor(chars = '') {
      this._chars = chars;
    }
  next() {
    var u = this._chars.toUpperCase();
    if (this._same(u,'Z')){
        var txt = '';
        var i = u.length;
        while (i--) {
            txt += 'A';
        }
        this._chars = 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 = this._nextLetter(l);
      if(z==='A'){
        this._chars = p.slice(0,-1) + this._nextLetter(q.slice(-1).charCodeAt(0)) + z;
          return p.slice(0,-1) + this._nextLetter(q.slice(-1).charCodeAt(0)) + z;
      } else {
        this._chars = p+z;
          return p + z;
      }
    }
  }
  prev() {
    var u = this._chars.toUpperCase();
    console.log("u "+u)
    var l = u.slice(-1).charCodeAt(0);
    var z = this._nextLetter(l);
    var rl = u.slice(1)
    var y = (rl == "A") ? "Z" :this._prevLetter(rl.charCodeAt(0))
      var txt = '';
      var i = u.length;
      var j = this._chars
      var change = false
      while (i--) {
        if(change){
          if (u[u.length-1] == "A"){
            txt += this._prevLetter(u[i].charCodeAt(0))
          }else{
            txt += u[i]
          }
          
        }else{
          if (u[u.length-1] == "A"){
            txt += this._prevLetter(u[i].charCodeAt(0))
            change = true
          }else{
            change = true
            txt += this._prevLetter(u[i].charCodeAt(0))
          }
        }
      }
      if(u == "A" && txt == "Z"){
        this._chars = ''
      }else{
        this._chars = this._reverseString(txt);
      }
      console.log(this._chars)
      return (j);
  }
  _reverseString(str) {
      return str.split("").reverse().join("");
  }
  _nextLetter(l){
      if(l<90){
          return String.fromCharCode(l + 1);
      }
      else{
          return 'A';
      }
  }
  _prevLetter(l){
    if(l<=90){
      if(l == 65) l = 91
        return String.fromCharCode(l-1);
    }
    else{
        return 'A';
    }
  }
  _same(str,char){
      var i = str.length;
      while (i--) {
          if (str[i]!==char){
              return false;
          }
      }
      return true;
  }
    
}
การใช้งาน
const ids = new StringIdGenerator();
ids.next(); 
ids.prev();