How to check if string contains only digits in JavaScript ?
Last Updated :
19 Mar, 2024
Checking if a string contains only digits in JavaScript involves verifying that every character in the string is a numerical digit (0-9).
Examples of checking if string contains only digits in JavaScript
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
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...