开发者

Javascript: Find out previous letter in alphabet

开发者 https://www.devze.com 2023-01-24 00:01 出处:网络
If I got a Letter in JavaScript, I\'d like to find out the previous letter in alphabetic order, so if input i开发者_如何学JAVAs \"C\", output must be \"B\". Are there any standard solutions or do i ha

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


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

精彩评论

暂无评论...
验证码 换一张
取 消