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

2
Hello, I am learning the JavaScript condition statements and I am doing an exercise, the purpose of the program is: The user types a letter, the program checks if 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's number

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

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

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

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

So I want to check if the string is a special character and if it is, print it for typing 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 (without Jquery if possible)

    
asked by anonymous 15.01.2018 / 19:04

1 answer

3

Using RegExp makes it easy to solve your problem I have developed a while that tests whether the given input is a special character or number, as long as it keeps asking for a letter, until the user inserts the letter and the loop is broken. Any doubt I am at disposal ... hint, Regexp is very important to facilitate validation, do not forget to dedicate 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!");
}
    
15.01.2018 / 19:22