Most web developers face the problem to check if a string is a number in JavaScript. If you are one of them, you are in the right place. Keep reading.📖
If you’re working with strings in JavaScript, you may need to determine whether a particular string represents a number. For instance, if you are designing a website and want to check different fields, whether entered values are numbers or not, then you are in the situation of what to do.
In this article, first of all, we’ll understand what strings and numbers in JavaScript are. Furthermore, we will discuss different ways to check whether a String is a number. What is NaN, and how isNaN, isInteger(), Regular Expressions, typeof, parseInt(), or parseFloat(), help us check if a string is a number or not. Now, let’s start giving answers to these questions one by one. 👇
Table of Contents
What Are String and Number in JavaScript?
In JavaScript, strings are used to store and manipulate text. We can write zero or any number of characters inside single or double quotes:
Code
let str = 'example';
In JavaScript, we use the let keyword to declare the variable. In JavaScript, we can write a number with or without decimals, but it is considered one type:
Code
let n= 20;
5 Ways to Check if String is a Number in JavaScript
We can check in JavaScript wheater a string is a number or not with the help of these three ways:
- The isNaN() method
- The isInteger() method
- The Regular Expressions
- Use the typeof operator
- Use the parseInt() or parseFloat() functions
Method 1: Using isNaN()
Before we discuss isNaN, let’s understand what NaN property is. NaN stands for Not a Number. NaN is used to checking whether a value entered is a number. For example,
Code
console.log(Math.sqrt(-256));
Output
NaN
The isNaN() method checks the type of a value. It returns true if the value passed to it is Not a Number. Let’s understand isNaN() method with the help of the following example.
Code
// Declare a variable with a string var str = "Text" // Check whether str string is a number or not if(isNaN(str)) { console.log(str + " is not a number "); } else { console.log(str + " is a number "); } // Declare a variable with string var num = 20; if(isNaN(num)) { console.log(num + " is not a number "); } else { console.log(num + " is a number "); }
Output
Text is not a number 20 is a number
Method 2: Using isInteger()
In JavaScript, the Number.isInteger() method determines whether the passed value is an integer. It returns true if the value is a number. Otherwise, it returns false.
General Syntax
Number.isInteger(number)
Let’s understand this method with the help of an example.
Code
function chkInteger(str) { if (typeof str !== 'string') { return false; } const num = Number(str); // Check the string if it contains a number or not if (Number.isInteger(num)) { return true; } return false; } // Return true console.log(chkInteger('1')); // Return false console.log(chkInteger('test'));
Output
true false
Method 3: Using Regular Expression(RegEx)
RegEx stands for Regular Expression in JavaScript. It is an object that describes a pattern of characters enclosed between slashes (/) to define a search. It performs pattern matching, search and replace functions on String.
A regular expression pattern contains simple characters or a combination of simple and special characters:
General regular expression
/^[0-9]+$/
In the above example, we used metacharacters, such as ^ and $. The ^ character marks represent the beginning of the string input, and the $ character marks represent the end of the string.
We use the plus symbol +, which matches one or more pattern occurrences and the brackets ([]) to find a range of characters. We can use \d in place of [0-9].
The following are the two methods that we can use with Regular Expressions.
- test()
- exec()
We can also use some of the String methods with it, such as:
- match()
- replace()
- search()
- split()
We can create Regular Expressions by calling the RegExp() constructor function. For example:
Code
const myregex = new RegExp(/^[0-9]+$/); // pass string so it will test console.log(myregex.test('123'));
Output
True
In this example, we pass 123 as a string, and regex compares it with the patterns(only decimal) we write here. It will return true in case of a number and false in case of no number. Here in the pattern, we can replace [0-9] with \d.
We can also write a function to check whether a string contains a number:
Code
console.log("Check whether a string is number"); function chkInteger(str) { return /^\d+$/.test(str); } console.log(chkInteger('Example')); console.log(chkInteger('20202'));
Output
Check whether a string is a number false true
Method 4: Use the typeof Operator
One simple way to check if a string is a number is to use the typeof
operator. This operator returns a string indicating the type of the operand. For example:
let str = '123'; console.log(typeof str); // Output: string let num = 123; console.log(typeof num); // Output: number
As you can see, the typeof
operator returns ‘string’ for a string value and ‘number’ for a numeric value. So, you can use this operator to check if a string is a number by checking if the typeof
the result is ‘number’.
Method 5: Use the parseInt() or parseFloat() Functions
A third option for checking if a string is a number is to use the parseInt()
or parseFloat()
function. These functions attempt to parse a string and return a numeric value. If the string cannot be parsed as a number, they return NaN
. For example:
let str = '123'; console.log(parseInt(str)); // Output: 123 let str2 = 'abc'; console.log(parseInt(str2)); // Output: NaN
As you can see, the parseInt()
function was able to parse the string ‘123’ and return a numeric value, but it was unable to parse the string ‘abc’ and returned NaN
instead.
Conclusion
To summarize the article, on how to check if a string is a number in JavaScript, we’ve discussed the five different ways, including isNaN() method, isInteger() method, regular expression, typeof operator, parseInt() or parseFloat() functions.
By using one of these methods, you can easily check if a string is a number in JavaScript. The method you choose will depend on your specific needs and the format of the strings you’re working with. Regardless of which method you choose, you should now have a better understanding of how to check if a string is a number in JavaScript.
Let’s have a quick review of the topics discussed in this article.
- What are Strings and Numbers?
- Ways to check if String is a number
- Use of isNaN() method
- Use of isInteger() method
- Use of Regular Expressions(RegEx)
- Use of typeof operator
- Use of parseInt() or parseFloat() functions
If this article is beneficial and solves your problem, don’t forget to share it with your coding partners—also, comment below 👇 which solution is more suitable in your case.
Happy coding!🥳