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?
From the doc prompt
result = window.prompt(text, 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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With