How can I make a function that takes a string and checks if it is a number string or if it includes letters/other characters? I have no idea what to do... RegExp takes too long so is there another way?
Asked
Active
Viewed 51 times
-2
-
4*"RegExp takes too long"* - In what sense? Regex is the obvious, simple way to do this: it would be one line of code with a short regex .... – nnnnnn Apr 09 '17 at 03:58
-
I'm not that used to RegExp , sorry. – person Apr 09 '17 at 04:04
-
I didn't know [`/^\d+$/`](http://stackoverflow.com/questions/9011524/javascript-regexp-number-only-check) was so long. – Spencer Wieczorek Apr 09 '17 at 04:06
-
1Possible duplicate of [Javascript regexp number only check](http://stackoverflow.com/questions/9011524/javascript-regexp-number-only-check) / [Is there a (built-in) way in JavaScript to check if a string is a valid number?](http://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number) – Spencer Wieczorek Apr 09 '17 at 04:08
4 Answers
0
You have to use isNaN()
function (is Not a Number). It will return you true if it's not a number (that mean that it contains letter) and false if it's one.
Source :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Sorikairo
- 798
- 4
- 19
0
You can check for isNaN
and see if value is number if you don't want to go with RegExp.
let inpArgs = Number.parseInt(input);
if(!Number.isNaN(inpArgs)){
// this check ensures that your input is number
// Do what you have to do
}
else{
// Handle the error
}
But I would prefer the one line check using RegExp any day like below.
if(/^\d+$/.test(Number(input))){
// this says your input is Number
}

Varun G
- 44
- 8
0
You can use typeof
oprator to check whether it is a number
or string
.
function(anything){
if(typeof(anything)==='number'){ //do something} }
if(typeof(anything)==='string'){ //do something} }
Hope I answer your question.
Thanks.

hardy
- 880
- 2
- 13
- 30
0
You can use typeof in JavaScript to identify input Like
alert(typeof <your input>); or var identity = typeof <your input>;
and whatever string alert that match in Condition Like
if (identity == <alert message>){do something}else{do something}

Dhruv Parmar
- 47
- 7