0

How do I increment a string "A" to get "B" in Javascript?

function incrementChar(c)
{


}
Etheryte
  • 24,589
  • 11
  • 71
  • 116
user1935724
  • 554
  • 1
  • 6
  • 18
  • 1
    What do you want to happen if you call `incrementChar('Z')`? – Dai Oct 02 '13 at 01:35
  • Possible duplicate of [What is a method that can be used to increment letters?](http://stackoverflow.com/questions/12504042/what-is-a-method-that-can-be-used-to-increment-letters) – SomethingDark Apr 22 '17 at 03:11

2 Answers2

10

You could try

var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'

So, in a function:

function incrementChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1)
}

Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
    var index = alphabet.indexOf(c)
    if (index == -1) return -1 // or whatever error value you want
    return alphabet[index + 1 % alphabet.length]
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
1
var incrementString = function(string, count){
    var newString = [];
    for(var i = 0; i < string.length; i++){
        newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
    }
    newString = newString.join('');
    console.log(newString);

    return newString;
}

this function also can help you if you have a loop to go through

Muhaimin
  • 1,643
  • 2
  • 24
  • 48