Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring that the value returned by Window.prompt contains only letters

Tags:

javascript

I'm trying to check to see if user input assigned to a variable can be checked to make sure it is a string, and not a number. I've tried using typeof(), but no matter what, the user input is tagged as a string, even if the user enters a number. For example:

var x = prompt("Enter a string of letters");
var y = typeof x;

if (y !== "string") {
    alert("You did not enter a string");
}

Is there something I could use that's similar to the NaN function, but for strings?

like image 371
Andyrc Avatar asked Nov 10 '14 03:11

Andyrc


Video Answer


1 Answers

From the doc prompt

result = window.prompt(text, value);
  • result is a string containing the text entered by the user, or the value null.
  • text is a string of text to display to the user. This parameter is optional and can be omitted if there is nothing to show in the prompt window.
  • value is a string containing the default value displayed in the text input field. It is an optional parameter. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value.

The return value is a string or null. In your example regardless user input, y always be a string or object.

In your case if you want to filter if user enter non-letters you can use a regular expression like:

var x = prompt("Enter a string of letters");

if (!/^[a-zA-Z]+$/.test(x) || !x) {
  alert("You did not enter a string");
}
like image 99
Alex Char Avatar answered Sep 19 '22 15:09

Alex Char