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

92,519

Solution 1

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'

Solution 2

Plain javascript should do the trick:

String.fromCharCode('A'.charCodeAt() + 1) // Returns B

Solution 3

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.

nextChar('yz'); // returns "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>

Solution 4

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

Solution 5

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.

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

How to use it:

charLoop("A", "K", function(char) {
    //char is one letter of the sequence
});

See this working demo

Share:
92,519
andyzinsser
Author by

andyzinsser

Founder at Arbiter

Updated on June 30, 2021

Comments

  • andyzinsser
    andyzinsser almost 3 years

    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"
    
  • Jasper
    Jasper about 9 years
    Hmm. Needs more jQuery.
  • Sean Kendle
    Sean Kendle over 7 years
    Changed if (same(u,'Z')){ to if (u == 'Z'){ and it works perfectly, thanks!
  • Ronnie Royston
    Ronnie Royston over 7 years
    Glad it worked and thanks for the feedback. Maybe that initial error was there bcs the function titled same(str,char) was not pasted in there? I dunno.
  • Sean Kendle
    Sean Kendle over 7 years
    Gotta be the case, same() is clearly a custom function. Oh well, == works, and if I wanted to be super sure, I could use ===, but I've tested it, and it's fine. Thanks again!
  • Amr Ashraf
    Amr Ashraf almost 7 years
    if you type zz you will get triple A is it a bug in the code ??
  • Ronnie Royston
    Ronnie Royston almost 7 years
    i don't think so? what comes after zz ? aaa right? i don't have excel installed on this machine (to double check) but it sounds right to me.
  • Trent
    Trent over 6 years
    Simple solution, but does not handle the occurrence of 'z' or 'Z'.
  • Daniel Thompson
    Daniel Thompson about 6 years
    kind of a buzzkill that it will go into special characters like /
  • sg28
    sg28 almost 6 years
    Pure Charm ,any suggestion on avoiding white spaces and special characters. coderByte has a question on this
  • Quentin 2
    Quentin 2 over 5 years
  • LeftOnTheMoon
    LeftOnTheMoon almost 5 years
    Exactly what I was looking for as I was trying to go through and pick out non-displaying unicode characters to an old-school IBM Code Page 437 font. You literally just saved me hours of character typing.
  • Bojidar Stanchev
    Bojidar Stanchev over 4 years
    Daniel Thompson this solution provides more than enough information, you can handle the corner cases yourself. After all, this is a "help-each-other" website, not do my job for free website.
  • Mark Davies
    Mark Davies over 4 years
    You may want to explain what exactly you have done here and how it helps rather than just having a block of code, thanks! - Maybe some helpful cmoments in the code?
  • LokeshKumar
    LokeshKumar over 4 years
    String.fromCharCode() it return the char code of letter.
  • JohnDavid
    JohnDavid over 4 years
    Took me a while to figure out how to make the Starting character to be an argument. I ended up using ._nextId = [chars.split('').findIndex(x=>x==start)]; Or start+1 if you want it to start 1 more than what you passed in.
  • Lyokolux
    Lyokolux almost 4 years
    Thanks for the class based solution :+1:
  • Gowtham Sooryaraj
    Gowtham Sooryaraj over 3 years
    need Prev() also
  • Gowtham Sooryaraj
    Gowtham Sooryaraj over 3 years
    Need Prev() also