How to get the next letter of the alphabet in Javascript?

后端 未结 7 1055
醉酒成梦
醉酒成梦 2021-01-03 18:20

I am build an autocomplete that searches off of a CouchDB View.

I need to be able to take the final character of the input string, and replace the last character wit

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 18:52

    I understand the original question was about moving the last letter of the string forward to the next letter. But I came to this question more interested personally in changing all the letters in the string, then being able to undo that. So I took the code written by Bipul Yadav and I added some more code. The below code takes a series of letters, increments each of them to the next letter maintaining case (and enables Zz to become Aa), then rolls them back to the previous letter (and allows Aa to go back to Zz).

    var inputValue = "AaZzHello";
    console.log( "starting value=[" + inputValue + "]" );
    
    var resultFromIncrementing = ""
    for( var i = 0; i < inputValue.length; i++ ) {
        var curr = String.fromCharCode( inputValue.charCodeAt(i) + 1 );
        if( curr == "[" ) curr = "A";
        if( curr == "{" ) curr = "a";
        resultFromIncrementing = resultFromIncrementing + curr;
    }
    console.log( "resultFromIncrementing=[" + resultFromIncrementing + "]" );
    
    inputValue = resultFromIncrementing;
    var resultFromDecrementing = "";
    for( var i2 = 0; i2 < inputValue.length; i2++ ) {
        var curr2 = String.fromCharCode( inputValue.charCodeAt(i2) - 1 );
        if( curr2 == "@" ) curr2 = "Z";
        if( curr2 == "`" ) curr2 = "z";
        resultFromDecrementing = resultFromDecrementing + curr2;
    }
    console.log( "resultFromDecrementing=[" + resultFromDecrementing + "]" );
    

    The output of this is:

    starting value=[AaZzHello]
    resultFromIncrementing=[BbAaIfmmp]
    resultFromDecrementing=[AaZzHello]
    

提交回复
热议问题