How to check if string contains only digits in JavaScript ?
Last Updated :
04 Jun, 2024
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
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
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
Please Login to comment...