最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Find out previous letter in alphabet - Stack Overflow

programmeradmin2浏览0评论

If I got a Letter in JavaScript, I'd like to find out the previous letter in alphabetic order, so if input is "C", output must be "B". Are there any standard solutions or do i have to create some special functions?

If I got a Letter in JavaScript, I'd like to find out the previous letter in alphabetic order, so if input is "C", output must be "B". Are there any standard solutions or do i have to create some special functions?

Share Improve this question edited Jan 11, 2013 at 14:52 Florian Müller asked Nov 4, 2010 at 9:00 Florian MüllerFlorian Müller 7,78526 gold badges83 silver badges121 bronze badges 2
  • 7 It probably doesn't matter for what you're doing, but keep in mind that the whole business of next/previous letters is very complicated if you're trying to do it properly, internationally. The solutions below are the standard ASCII/English-centric approach which everyone's been doing for decades, but which probably wouldn't satisfy in Turkey or Japan... – Will Dean Commented Nov 4, 2010 at 9:11
  • I have to say that this one will ever only be used in german, english, french or italian, but never with another language with other letters. And to say too, this isn't an user-input, so it is given with the program (shipyard, fieldnames are e.g. B4, and I was looking for C4) – Florian Müller Commented Dec 8, 2010 at 10:03
Add a comment  | 

4 Answers 4

Reset to default 16
var ch = 'b';
String.fromCharCode(ch.charCodeAt(0) - 1); // 'a'

And if you wanted to loop around the alphabet just do a check specifically for 'a' -- loop to 'z' if it is, otherwise use the method above.

This should work in some cases, you might need to tweak it a bit:

function prevLetter(letter) {
    return String.fromCharCode(letter.charCodeAt(0) - 1);
}

If letter is A, the result is @, so you need to add some sanity checking if you want it to be foolproof. Otherwise should do the job just fine.

The full function from Tatu's comment would be

function prevLetter(letter) {
    if (letter === 'a'){ return 'z'; }
    if (letter === 'A'){ return 'Z'; }
    return String.fromCharCode(letter.charCodeAt(0) - 1);
}

Something like this should work.

function prevLetter(letter) {
    var code = letter.charCodeAt(0);
    var baseLetter = "A".charCodeAt(0); 
    if (code>"Z".charCodeAt(0)) {
        var baseLetter = "a".charCodeAt(0); 
    }
    return String.fromCharCode((code-baseLetter+25)%26+baseLetter);
}
发布评论

评论列表(0)

  1. 暂无评论