What is a method that can be used to increment let

2020-01-24 20:58发布

Does anyone know of a Javascript library (e.g. underscore, jQuery, MooTools, etc.) that offers a method of incrementing a letter?

I would like to be able to do something like:

"a"++; // would return "b"

13条回答
我想做一个坏孩纸
2楼-- · 2020-01-24 21:20

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;

查看更多
劫难
3楼-- · 2020-01-24 21:21

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"));

查看更多
SAY GOODBYE
4楼-- · 2020-01-24 21:22

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'
查看更多
闹够了就滚
5楼-- · 2020-01-24 21:25

Make a function with {a: 'b', b: 'c', etc} in a closure:-

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

usage:-

nextChar('a')

Adding uppercase and digits:-

let nextCh = (
    (alphabeta, s) => (
        [alphabeta, alphabeta.toUpperCase(), "01234567890"]
            .forEach(chars => chars.split('')
               .reduce((a,b) => (s[a]=b, b))), 
        c=> s[c] 
    )
)("abcdefghijklmopqrstuvwxyza", {});

p.s. In some versions of Javascript, you can use [...chars] instead of chars.split('')

查看更多
萌系小妹纸
6楼-- · 2020-01-24 21:28

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.


Unique string generator

(Updated 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'
查看更多
7楼-- · 2020-01-24 21:28

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 ...

查看更多
登录 后发表回答