Check if a string is a number and check if it is a special character

Asked

Viewed 827 times

2

Hello, I’m learning the Javascript condition commands and I’m doing an exercise,: The user types a letter, the program checks whether the letter is a vowel or a consonant,so I made this code:

var letra = prompt("Digite uma letra:");

//passando variável para minúscula 
letra = letra.toLowerCase();

//checando vogais

if(letra == "a" || letra == "e" || letra == "i" ||       letra == "o" || letra == "u"){
    document.write(letra + " é uma vogal");
}
else{
    document.write(letra + " é uma consoante!");
}

Only I found two problems

1.Check if it is number

For example, if the user type: 4 the result is: 4 is a consonant!

For program 4 it’s not vowel, so it’s consonant, I want to check if the string is a number and print to the user who is to type only letters

2.Check if they are other characters ex;#%*

For example, if the user type: # the result is: # is a consonant

Soon, I want to check if the string is a special character and if it is, print it out so it can type only letters

*I want to create two Else if in the program to check if the string is a number and if the string is a special character

*I’m learning Javascript and it’s an exercise with if/Else so if possible I want a solution with pure Javascript(No Jquery if possible)

1 answer

2


Using Regexp makes everything easier, to solve your problem I developed a while testing whether the input provided is a special character or number, while it is still asking for a letter, until the user inserts the letter and the loop is broken. Any doubt I am available... tip, Regexp is quite important to facilitate validation, do not forget to devote time to it.

var regexVogal = /[aeiou]/i; //Regex para capturar vogais
var regexEspecialCharacters = /(\W)|(\d)/i; //Regex para detectar caracteres especials
var letra = prompt("Digite uma letra:");

//Enquanto for caracter especial
while(regexEspecialCharacters.test(letra)){
  letra = prompt("Digite APENAS uma letra:");
}
//passando variável para minúscula 
letra = letra.toLowerCase();

//checando vogais
if(regexVogal.test(letra)){
   document.write(letra + " é uma vogal");
}else{
  document.write(letra + " é uma consoante!");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.