Setting a character limit on a prompt box Javascript

Viewed 41

I would like to know if there is a way to pre-set the length of the characters in the javascript prompt. So that I can enter only one character and no more

var carattere = prompt("inserte a character");


console.log(carattere);

if (carattere=="a" || carattere=="e" || carattere=="i" || carattere=="o" || carattere=="u") {
    window.alert("the character is a Vowel");
}else if(carattere=="y"){
    window.alert("Y can be consonant or vowel");
}else{
    window.alert("the character is a consonant");
}

1 Answers

Since prompt() stores a string by default, You could check for the length of the prompt using length. Like this:

const carattere = prompt("Insert a character");


if (carattere.length === 1) {
  if (carattere === "a" || carattere === "e" || carattere === "i" || carattere === "o" || carattere === "u") {
    window.alert("The character is a Vowel");
  } else if (carattere === "y") {
    window.alert("Y can be consonant or vowel");
  } else {
    window.alert("The character is a consonant");
  }
} else {
  console.log("Please limit the input to a single character");
}

Note: Typing a number character gets identified as consonant. You might want to add an additional check (like a regular expression) to account for that.

Related