JavaScript: Check if variable is a number

Example 1: Using regular expression:

Check if inputed text is a number using Regex
<input type="text" id="text">
<button type="button" onClick="checkisNumber()">Check</button>
<div id="result"></div>

function checkisNumber() {
 var no = document.getElementById("text").value;
 var isNoRegex=/^\d*(\.)?(\d{1,})?$/;
 if(!no.match(isNoRegex)) {
 	document.getElementById("result").innerHTML = no + " is not a number";
 } else {
 	document.getElementById("result").innerHTML = no + " is a number";

Example 2: Using isNaN() function

var number1 = 10;
var number2 = "10a";
var number3 = "10";
var number4 = 10.1;

console.log(number1+" is a number? " + !isNaN(number1));
console.log(number2+" is a number? " + !isNaN(number2));
console.log(number3+" is a number? " + !isNaN(number3));
console.log(number4+" is a number? " + !isNaN(number4));
"10 is a number? true"
"10a is a number? false"
"10 is a number? true"
"10.1 is a number? true"

Example 3: Using typeof operator

var number1 = 1234;
var number2 = "101bac";
var number3 = "abc";
var number4 = "10.1123";

console.log(number1+" is a " + typeof number1);
console.log(number2+" is a " + typeof number2);
console.log(number3+" is a " + typeof number3);
console.log(number4+" is a " + typeof number4);
"1234 is a number"
"101bac is a string"
"abc is a string"
"10.1123 is a string"

Recent Posts:

Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.