views:

279

answers:

2

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 with the next letter of the english alphabet. (No need for i18n here)

For Example:

  • Input String = "b"
  • startkey = "b"
  • endkey = "c"

OR

  • Input String = "foo"
  • startkey = "foo"
  • endkey = "fop"

(in case you're wondering, I'm making sure to include the option inclusive_end=false so that this extra character doesn't taint my resultset)


The Question

  • Is there a function natively in Javascript that can just get the next letter of the alphabet?
  • Or will I just need to suck it up and do my own fancy function with a base string like "abc...xyz" and indexOf()?
+5  A: 
my_string.substring(0,my_string.length-1)+String.fromCharCode(my_string.charCodeAt(my_string.length-1)+1)
icktoofay
but watch for the edge case of z/Z`z +1 = {` and`Z +1 = [`
Gaby
For what the person asking the question is doing, I'd assume `{` and `[` aren't problems.
icktoofay
@ictoofay Thanks, this worked right away.@Gaby Thanks for the heads up!
Dominic Barnes
+2  A: 

// This will return A for Z and a for z.

function nextLetter(s){
    return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
        var c= a.charCodeAt(0);
        switch(c){
            case 90: return 'A';
            case 122: return 'a';
            default: return String.fromCharCode(++c);
        }
    });
}
kennebec