What is a method that can be used to increment letters?

前端 未结 14 2810
我在风中等你
我在风中等你 2020-11-27 04:19

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 somet

14条回答
  •  臣服心动
    2020-11-27 04:46

    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'
    

提交回复
热议问题