Open In App

JavaScript Program to Check if a String Contains Any Digit Characters

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 contains any digit characters, along with understanding their basic implementations.

Examples of Checking if a String Contains Any Digit Characters

1. Using for Loop

Iterate through the string character by character using a for loop and check each character’s Unicode value to determine if it’s a digit.

Syntax:

  for (let i = 0; i < text.length; i++) {
if (text[i] >= '0' && text[i] <= '9') {
return true;
}
}

Example: In this example The function iterates through each character in the string, checking if it falls within the range of digits (‘0’ to ‘9’). Returns true if any digit found, else false.

Javascript
function checkDigits(str) {
  for (let i = 0; i < str.length; i++) {
    if (str[i] >= '0' && str[i] <= '9') {
      return true;
    }
  }
  return false;
}

const input = "Geeks for Geeks 123 numbers.";
console.log(checkDigits(input));

Output
true

2.Using Regular Expressions

Use a regular expression to search for any digit characters in the string. Regular expressions provide a concise and powerful way to find patterns in text.

Syntax:

 const digitPattern = /\d/;

Example: In this example The function utilizes a regular expression pattern to check if any digit (\d) is present in the string, returning true if found, otherwise false.

Javascript
function checkDigits(str) {
  const digitPattern = /\d/;
  return digitPattern.test(str);
}

const input = "Geeks for Geeks";
console.log(checkDigits(input));

Output
false

3.Using filter() and isNaN()

This approach Uses the filter() method to create an array of digit characters and check if the array’s length is greater than 0.

Syntax:

str.split('').filter(char => !isNaN(parseInt(char))).length > 0

Example: In this example the function splits the string into characters, filters non-digit characters, and returns true if any digit is found.

JavaScript
function containsDigit(str) {
    return (
        str
            .split("")
            .filter(
                (char) => !isNaN(parseInt(char))
            ).length > 0
    );
}

let str = "Hello  GeeksforGeeks123";
console.log(containsDigit(str));

Output
true

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads