Check if String Is a Number or Not in JavaScript
Tutorial on how can I check if a string is a valid number or not in JavaScript.
In this article will be on how to check if a given value is a number or NaN (Not-a-number).
In programming language, a number is a datatype that denotes a integer or a floating point. And a String can be define as a sequence of character which includes both letters and numbers. Example: "Hello", "123abc" etc.
So let's check how we can find if a string consist only number using the method below:
Using isNaN() to check if a JavaScript String has a Number.
The isNaN() function determine whether a given value is a number or NaN (Not-a-Number).
If the output returns true, that means it's NaN value and if it's false, it's a valid number.
Syntax:
isNaN(value)
Example:
console.log(isNaN('2022')) // false console.log(isNaN('computer')) // true console.log(isNaN('123abc')) // true
We can write a function isNumber() that will return true if the string is a number.
function isNumber(val){ if(isNaN(val)) { return false } return true } console.log(isNumber('2022')); // true console.log(isNumber('computer')); // false console.log(isNumber('123abc')); //false
Using Number() function to check if a string is a number
The Number() function convert a given value of other datatype (eg: string etc) to a number representing the object 's value.
Syntax:
new Number(value)
It will return number if the string contains only number or else it will return NaN (Not-a-Number).
Example:
console.log(Number('2022')) // true console.log(Number('hello')) //NaN console.log(Number('123abc')) //NaN
Using Unary Plus (+) operation to determine whether a string is numeric in JavaScript
The + operator coverts a string to a number. It will return the number value of the string or else it will return NaN (Not-a-Number) if the given value is not a pure number.
Example:
console.log(+'2022') // 2022 console.log(+'hello') // NaN console.log(+'abc123') //NaN
Related Topics:
Check if a value is a number in JavaScript
Related Posts
Capitalize First Letter of a String - JavaScript
This article is about how to capitalize the first letter of a string using JavaScript.
Check if String starts with a space in JavaScript
Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.
JavaScript - Detect if a string contains any space
FInd out how to detect if a string contains any white space using regex test() method and string indexOf() method in Javascript.
Split a String into chunks of N character into an array in JavaScript
Find out how to split String into Substrings by length of N characters in JavaScript using split(), match() and substr() methods.
