ArticleZip > Check If String Contains Only Digits

Check If String Contains Only Digits

When working with strings in programming, it's often useful to verify whether a string contains only digits. This can be handy when you need to validate user input for phone numbers, PIN codes, or any other numerical data. In this article, we'll explore a simple and efficient way to check if a string contains only digits in various programming languages.

### JavaScript:
In JavaScript, you can use the built-in `isNaN` function along with a regular expression to check if a string contains only digits. Here's a code snippet that demonstrates this approach:

Javascript

function containsOnlyDigits(input) {
  return /^d+$/.test(input);
}

console.log(containsOnlyDigits("12345")); // Output: true
console.log(containsOnlyDigits("abc123")); // Output: false

In this code, the `^d+$` regular expression pattern matches strings that contain only digits. The `test` method then checks if the input string satisfies this pattern and returns `true` if it does.

### Python:
Python offers a straightforward way to check if a string contains only digits using the `isdigit` method along with a loop. Here's an example code snippet in Python:

Python

def contains_only_digits(input):
    return all(char.isdigit() for char in input)

print(contains_only_digits("12345"))  # Output: True
print(contains_only_digits("abc123"))  # Output: False

The `isdigit` method in Python checks if each character in the input string is a digit, and the `all` function ensures that all characters meet this criteria for the entire string.

### Java:
In Java, you can use the `Character.isDigit` method inside a loop to verify if a string contains only digits. Here's how you can do it:

Java

public static boolean containsOnlyDigits(String input) {
    for (char c : input.toCharArray()) {
        if (!Character.isDigit(c)) {
            return false;
        }
    }
    return true;
}

System.out.println(containsOnlyDigits("12345")); // Output: true
System.out.println(containsOnlyDigits("abc123")); // Output: false

By iterating through each character in the input string and checking if it is a digit using `Character.isDigit`, this Java method accurately determines if the string comprises only digits.

### Conclusion:
Ensuring that a string contains only digits is a common task in software development. Whether you're working in JavaScript, Python, Java, or any other programming language, these simple yet effective methods provide a reliable way to validate user input and handle numerical data efficiently. By leveraging the appropriate language features and techniques, you can enhance the robustness of your applications and deliver a seamless user experience.