The Wayback Machine - https://web.archive.org/web/20240822183720/https://www.geeksforgeeks.org/how-to-check-if-string-contains-only-digits-in-javascript/
Open In App

How to check if string contains only digits in JavaScript ?

Last Updated : 04 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Checking if a string contains only digits in JavaScript involves verifying that every character in the string is a numerical digit (0-9).

1. Using Regular Expression

Regular expressions (regex) are patterns used to match character combinations in strings. In JavaScript, they are typically defined between forward slashes /, like /pattern/. To check if a string contains only digits, you can use the regex pattern ^\d+$.

Example: The containsOnlyDigits function uses a regular expression (/^\d+$/) to test if a string consists only of digits. It returns true if the string matches the pattern (only digits), and false otherwise.

JavaScript
function containsOnlyDigits(str) {
    return /^\d+$/.test(str);
}

console.log(containsOnlyDigits("123")); // Output: true
console.log(containsOnlyDigits("123abc")); // Output: false

Output
true
false

2. Using isNaN() Function

The isNaN() function in JavaScript checks if a value is “Not-a-Number” (NaN). By converting a string to a number using parseFloat(), it can determine if the string contains only digits. If the conversion is successful, it returns false, indicating that the string contains only digits. Otherwise, it returns true.

Example: The containsOnlyDigits function checks if a string contains only digits by attempting to convert it to a number using parseFloat(). It returns true if successful, indicating the string contains only digits, otherwise false.

JavaScript
function containsOnlyDigits(str) {
  return !isNaN(str) && !isNaN(parseFloat(str));
}

console.log(containsOnlyDigits("123")); // Output: true
console.log(containsOnlyDigits("123abc")); // Output: false

Output
true
false

3. Using Array.prototype.every()

The Array.prototype.every() method tests whether all elements in the array pass the test implemented by the provided function. We can split the string into an array of characters and check if every character is a digit.

Example: The containsOnlyDigits function splits the string into an array of characters and uses the every() method to check if every character is a digit using the isDigit helper function.

JavaScript
function isDigit(char) {
    return char >= '0' && char <= '9';
}

function containsOnlyDigits(str) {
    return str.split('').every(isDigit);
}

console.log(containsOnlyDigits("123")); // Output: true
console.log(containsOnlyDigits("123abc")); // Output: false
// Nikunj Sonigara

Output
true
false


Similar Reads

JavaScript Program to Check if a String Contains only Alphabetic Characters
We will check if a string contains only alphabetic characters in JavaScript. We will verify that all characters within the string are letters of the alphabet (A-Z or a-z) and do not include any digits, symbols, or other non-alphabetic characters. Below are the approaches to check if a string contains only alphabetic characters in JavaScript: Table
4 min read
JavaScript Program to Check if an Array Contains only Unique Values
In this article, we are given an array, Our task is to find whether the elements in an array are unique or not. Examples: Input 1: 7,8,1,5,9 Output: true Input2: 7,8,1,5,5 Output: falseIn Input 1, elements 7,8,1,5,9 are distinct from each other and they were unique, there was no repetition of elements hence the array contains unique values. So the
4 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
How to check whether a string contains a substring in JavaScript ?
A substring is a portion of a string. It represents a sequence of characters extracted from a larger string. A substring can be as short as a single character or extend to multiple characters. There are several approaches to check whether a string contains a substring or not: Table of Content Checking for Substring with includes() MethodChecking fo
3 min read
How to Check if a String Contains a Valid URL Format in JavaScript ?
A string containing a valid URL format adheres to standard conventions, comprising a scheme (e.g., "http://" or "https://"), domain, and optionally, a path, query parameters, and fragments. Ensuring this format is crucial for data consistency and accurate handling of URLs in applications. There are several methods that can be used to check if a str
2 min read
JavaScript Program to Check if a String Contains any Special Character
This article will demonstrate the methods to write a JavaScript Program to check if a String contains any special characters. Any string that contains any character other than alphanumeric and space includes the special character. These special characters are '!', '@', '#', '$', '%', '^', '&amp;', '*', '(', ')', '-', '+', '=', '{', '}', '[', ']', '
5 min read
Check if a String Contains any Whitespace Characters using JavaScript
In this article, we are given a string str, you need to find whether the given string contains whitespace characters or not in JavaScript. Whitespaces can occur at any position whether at the beginning or in between or at the end of the string. Example 1: Input:str = Hi I am a Geek Output:The string contains whitespace charactersExplanation: In the
5 min read
JavaScript Program to Check if a String Contains Any Digit Characters
In this article, we will see how to check if a string contains any digit characters in JavaScript. Checking if a string contains any digit characters (0-9) in JavaScript is a common task when we need to validate user input or perform specific actions based on the presence of digits in a string. We will explore every approach to check if a string co
5 min read
How to check if a String contains a Specific Character in PHP ?
In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common approaches: Table of Content Using strpos( ) functi
2 min read
How to Check Whether an Array Contains a String in TypeScript ?
To check whether an array contains a string in typescript we have a different approach. In this article, we are going to learn how to check whether an array contains a string in typescript. Below are the approaches to check whether an array contains a string in typescript: Table of Content Approach 1: Using Array.includes() methodApproach 2: Using
4 min read
How to check if a String Contains a Substring in PHP ?
A string is a collection of given characters and a substring is a string present in a given string. In this article, we are going to check if the given string contains a substring by using the PHP strpos() function. Syntax: strpos($original_string,$sub_string);Parameters: original_string : The input stringsub_string : The substring searched in the
3 min read
How to check a URL contains a hash or not using JavaScript ?
In this article, the task is to check whether an URL contains or not. This can be done by using the Location hash property in JavaScript. It returns the string which represents the anchor part of a URL including the hash ‘#’ sign. Syntax: window.location.hash Example: This example uses the hash property to check if the URL contains hash or not usin
1 min read
Check an array of strings contains a substring in JavaScript
Checking if an array of strings contains a substring in JavaScript involves iterating through each string in the array and examining if the substring exists within any of them. This process ensures efficient detection of the substring's presence within the array. These are the following ways to do this: Table of Content Using includes() method and
4 min read
How to check an Array Contains an Object of Attribute with Given Value in JavaScript ?
Sometimes, when working with an array of objects in JavaScript, we need to determine whether an object with a specific attribute value exists in the array. This can be useful when filtering or searching for specific objects in the array. Below are the common methods to determine if the array contains an object with an attribute. Table of Content Us
4 min read
How to find if an array contains a specific string in JavaScript/jQuery ?
In order to Check if an array contains a specific string be done in many ways in Javascript. One of the most common methods to do this is by using the traditional for loop. In Javascript, we have several other modern approaches which help in finding a specific string in an array to iterate the array some more methods include using the indexOf()  me
5 min read
JavaScript to keep only first N characters in a string
In this article, we have given a string and the task is to keep only the first n characters of the string using JavaScript. There are various methods to solve this problem, some of which are discussed below: Methods to keep only First N characters in a String:Table of Content Method 1: Using substring() MethodMethod 2: Using slice() MethodMethod 3:
5 min read
How to check an element contains a class using jQuery?
Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes. Syntax: $('element').hasClass('className') Example: &lt;!
2 min read
How to check an element contains specific class in jQuery ?
In this article, we will see how to check if an element contains a specific class using jQuery. The Jquery function called hasClass() function will be used, which will return a boolean result if the particular element contains any specific class. Note that we can check for multiple classes available in a single tag. Syntax: $(&lt;slector&gt;).hasCl
3 min read
Javascript Program to Check if all array elements can be converted to pronic numbers by rotating digits
Given an array arr[] of size N, the task is to check if it is possible to convert all of the array elements to a pronic number by rotating the digits of array elements any number of times. Examples: Input: {321, 402, 246, 299} Output: True Explanation: arr[0] ? Right rotation once modifies arr[0] to 132 (= 11 × 12). arr[1] ? Right rotation once mod
3 min read
How to return true if the parent element contains the child element in JavaScript ?
In JavaScript, children property returns an array of those elements which are children of a given element. In order to check whether the parent element (say x) contains a child element (say y), we can use the children property to get the array of all children of x and then check whether the array obtained contains y. To get the child element of a p
2 min read
How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ?
In this article, we are going to learn about comparing two objects to determine if the first object contains equivalent property values to the second object, In JavaScript, comparing the values of two objects involves checking if they have the same properties with corresponding values. Given two objects obj1 and obj2 and the task are to check that
6 min read
Javascript Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Javascript Program to Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
4 min read
Javascript Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview Recommended: Please solve it on “PRACTICE ” f
2 min read
How to check a given string is an anagram of another string in JavaScript ?
In this article, we will learn how to check a given string is an anagram of another string in JavaScript. Before that, we should learn what is an anagram. An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different term or phrase. Some of the examples are given below
3 min read
How to check if a string "StartsWith" another string in JavaScript ?
In JavaScript, the 'startsWith()' method is a built-in method that allows one to check whether a string starts with a specified substring. Syntax: It takes a single argument, which is the substring we want to check whether the string starts with. string.startsWith(searchString[, position])Approach 1: Using startWith methodThe 'searchString' paramet
2 min read
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string. Example: Input: "101010"Output: True, binary stringInput: "110211"Output: Falee,Explanati
4 min read
Check if a string is a valid JSON string using JavaScript
We will be given a string and we need to validate whether the given string is a valid JSON string or not. JSON string is the same as a javaScript object and it must follow the syntax of that object. If the syntax is correct then we have to return true or we have to return false. Methods to Check if a String is Valid JSON String: Table of Content Us
5 min read
How to validate if input in input field has full width string only using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only full-width strings are allowed. We can also validate these input fields to only accept full-width s
4 min read
How to compare date part only without comparing time in JavaScript?
To obtain date and time in javascript, we have the Date() class. We access Date() class by creating its objects. Date() class returns date and time both combined. There are four ways of instantiating a date: Syntax: var d = new Date(); //returns the present date and time or var d = new Date(milliseconds); //to set a specific date or var d = new Dat
4 min read
Article Tags :
three90RightbarBannerImg