Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether variable is number or string in JavaScript

Does anyone know how can I check whether a variable is a number or a string in JavaScript?

like image 554
Jin Yong Avatar asked Aug 20 '09 02:08

Jin Yong


People also ask

How do you tell if a string is a number JavaScript?

Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.

How do you check if a variable is a string in JS?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string.

How do you check if a value is Not-a-Number in JavaScript?

isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.


1 Answers

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string typeof 123;           // number 

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;  _.isString = function (obj) {   return toString.call(obj) == '[object String]'; } 

This returns a boolean true for the following:

_.isString("Jonathan"); // true _.isString(new String("Jonathan")); // true 
like image 142
Sampson Avatar answered Oct 08 '22 06:10

Sampson