Newtonian
Newtonian

Reputation: 3

Javascript to set an alphabetical letter equal to the one before

I wanted to make a program in where we can say that every letter, is equal to the one before it, except - the letter a, which will be set to 0. However, as I am a beginner, Im not quite sure where to begin. I believe something such as a Javascript switch statement ought to do the task:

ar a,...,z;
switch (~~~~~~~) {
case 0:
    "a" = "0";
    break;
case 1:
    "b" = "a";
    break;
case 2:
    "c" = "b";
    break;
case n:
    "letter" = "letter before it";
    break;
    ...}

My question is how I can turn the Pseudo Code above into real code?

Upvotes: 0

Views: 1100

Answers (3)

Dimos
Dimos

Reputation: 8908

You can dynamically retrieve the previous letter by getting the ASCII code and reducing by 1:

function previousLetter(letter){
    if(letter == 'a') return 0;
    else return String.fromCharCode(letter.charCodeAt(0)-1)
}

> previousLetter('b')
'a'
> previousLetter('a')
0

Upvotes: 0

Raider
Raider

Reputation: 394

You must put off the " symbol:

var a,...,z;
switch (~~~~~~~) {
case 0:
    a = "0";
    break;
case 1:
    b = a;
    break;
case 2:
    c = b;
    break;
case n:
    letter = "letter before it";
    break;
    ...}

This code, in case 1 (for example) set the variable b equal to variable a, but actually in this code all variables aren't initialized so allways be null, you must initialize it first like this:

a = "a";

or directly put in the correct case:ç

case 1:
    b = "a";
    break;

Upvotes: 0

dpanshu
dpanshu

Reputation: 463

You do not need to use case for every character. Just compare the ASCII value of the character to ASCII value -1 (which is the previous character)

str="a";
if(str.charCodeAt(0)==(str.charCodeAt(0)-1))
alert('true');

You can filter the ASCII value 97 (a) to be ignored for the comparison

Upvotes: 2

Related Questions