JavaScript Program to Extract Strings that contain Digit
Last Updated :
09 Jul, 2024
We are given a Strings List, and the task is to extract those strings that contain at least one digit.
Example:
Input: test_list = [‘gf4g’, ‘is’, ‘best’, ‘gee1ks’]
Output: [‘gf4g’, ‘gee1ks’]
Explanation: 4, and 1 are respective digits in a string.
Input: test_list = [‘gf4g’, ‘is’, ‘best’, ‘geeks’]
Output: [‘gf4g’]
Explanation: 4 is a digit in the string.
This approach uses filter() to iterate over each string in the array. For each string, split('') is used to convert it into an array of characters. Then, some() is applied to the array of characters to check if at least one character can be converted to a number using parseInt() without resulting in NaN.
Example: This example shows the use of the above-explained approach.
JavaScript
const strings = ["abc", "def456", "hgt7ju", "gfg", "789xyz"];
const result = strings.filter(str => str.split('').some(char => !isNaN(parseInt(char))));
console.log(result);
Output[ 'def456', 'hgt7ju', '789xyz' ]
In this approach the code checks for strings in an array that contains any digit. It uses the `filter` method to iterate through the array and a regular expression pattern, `/d`, to match any digit in each string. The result, an array of strings containing digits is stored in the variable `res` and then printed in the console.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing list
let test_list =
['gf4g', 'is', 'best', '4', 'gee1ks'];
// Printing original list
console.log("The original list is : " + test_list);
// Using regular expression to search for pattern \d
// which represents a digit in the string
let pattern = /\d/;
let res = test_list.filter((i) => pattern.test(i));
// Printing result
console.log("Strings with any digit : " + res);
OutputThe original list is : gf4g,is,best,4,gee1ks
Strings with any digit : gf4g,4,gee1ks
Using loop and replace() method to extract strings that contain digit
In this approach we are definig a function `fun` that checks if a string contains any digit using a loop and the `replace`method. The main script initializes an array, iterates through it, and collects strings containing digits using the`fun`function. The resulting array`res` is printed, that is containing strings with digits from the original list.
Example: This example shows the use of the above-explained approach.
JavaScript
function fun(s) {
const digits = "0123456789";
let x = s;
for (let i of digits) {
s = s.replace(new RegExp(i, 'g'), "");
}
if (x.length !== s.length) {
return true;
}
return false;
}
// Initializing list
let test_list = ['gf4g', 'is', 'best', '4', 'gee1ks'];
// Printing original list
console.log("The original list is : " + test_list);
let res = [];
for (let i of test_list) {
if (fun(i)) {
res.push(i);
}
}
// Printing result
console.log("Strings with any digit : " + res);
OutputThe original list is : gf4g,is,best,4,gee1ks
Strings with any digit : gf4g,4,gee1ks
Using Array.prototype.filter and a Loop
This approach filters an array of strings using Array.prototype.filter and a loop. It iterates through each string, checks each character, and returns true if any character is a digit (char >= '0' && char <= '9'), thereby extracting strings containing digits.
Example: In this example The function extractStringsContainingDigit filters an array to return strings containing at least one digit.
JavaScript
function extractStringsContainingDigit(arr) {
return arr.filter(str => {
for (const char of str) {
if (char >= '0' && char <= '9') {
return true;
}
}
return false;
});
}
let input = ["hello", "world1", "test", "abc123"];
console.log("The original List: " + input)
console.log("String with any digit: " + extractStringsContainingDigit(input));
OutputThe original List: hello,world1,test,abc123
String with any digit: world1,abc123
Using Array.prototype.reduce method
This approach utilizes the reduce method to iterate over each string in the array. For each string, it checks if it contains any digit using a regular expression (/\d/). If a string contains at least one digit, it is added to the result array. Finally, the function returns the result array containing strings with digits.
JavaScript
// Function to extract strings containing at least one digit
function extractStringsWithDigit(arr) {
return arr.reduce((result, str) => {
// Using regular expression to test if the string contains any digit
if (/\d/.test(str)) {
result.push(str);
}
return result;
}, []);
}
const test_list = ['gf4g', 'is', 'best', '4', 'gee1ks'];
console.log("Original List:", test_list);
console.log("Strings with any digit:", extractStringsWithDigit(test_list));
OutputOriginal List: [ 'gf4g', 'is', 'best', '4', 'gee1ks' ]
Strings with any digit: [ 'gf4g', '4', 'gee1ks' ]
Approach: Using Array.prototype.some with Regular Expression Check
In this approach, we utilize the Array.prototype.some method along with a regular expression check within the filter method to efficiently identify strings containing at least one digit. The some method will iterate through each character in the string and check if it matches the digit pattern using the regular expression.
Example: This example demonstrates the use of Array.prototype.some with a regular expression to extract strings that contain at least one digit.
JavaScript
function extractStringsContainingDigit(test_list) {
return test_list.filter(str => str.split('').some(char => /\d/.test(char)));
}
// Test cases
const testList1 = ['gf4g', 'is', 'best', 'gee1ks'];
const testList2 = ['gf4g', 'is', 'best', 'geeks'];
console.log(extractStringsContainingDigit(testList1)); // Output: ['gf4g', 'gee1ks']
console.log(extractStringsContainingDigit(testList2)); // Output: ['gf4g']
Output[ 'gf4g', 'gee1ks' ]
[ 'gf4g' ]
Similar Reads
JavaScript Program to Test if Kth Character is Digit in String
Testing if the Kth character in a string is a digit in JavaScript involves checking the character at the specified index and determining if it is a numeric digit.Examples:Input : test_str = âgeeks9geeksâ, K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str =
5 min read
JavaScript - Check if a String Contains Any Digit Characters
Here are the various methods to check if a string contains any digital character1. Using Regular Expressions (RegExp)The most efficient and popular way to check if a string contains digits is by using a regular expression. The pattern \d matches any digit (0-9), and with the test() method, we can ea
4 min read
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers
In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and nu
4 min read
JavaScript Program to Check Whether a Number is Harshad Number
A Harshad number (also called Niven number) is a number that is divisible by the sum of its digits. In other words, if you take a number, sum up its digits, and if the original number is divisible by that sum, then it's a Harshad number. For example, 18 is a Harshad number because the sum of its dig
2 min read
JavaScript - How To Check if String Contains Only Digits?
A string with only digits means it consists solely of numeric characters (0-9) and contains no other characters or symbols. Here are the different methods to check if the string contains only digits.1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string co
3 min read
Extract a Number from a String using JavaScript
We will extract the numbers if they exist in a given string. We will have a string and we need to print the numbers that are present in the given string in the console.Below are the methods to extract a number from string using JavaScript:Table of ContentUsing JavaScript match method with regExUsing
4 min read
How to check if string contains only numeric digits in PHP ?
Given a string, the task is to check whether the string contains only numeric digits in PHP. It is a common task to verify whether a given string consists of only numeric digits in PHP. It can be useful when dealing with user input validation, form submissions, or data processing tasks where numeric
4 min read
How to write a cell phone number in an international way using JavaScript ?
E.164 format is used to convert a phone number into an international format. It is an internationally recognized standard that defines a general numbering plan. The international number format according to E.164 is as follows: [+][country code][area code][local phone number] +: Plus sign country cod
3 min read
JavaScript - Strip All Non-Numeric Characters From String
Here are the different methods to strip all non-numeric characters from the string.1. Using replace() Method (Most Common)The replace() method with a regular expression is the most popular and efficient way to strip all non-numeric characters from a string.JavaScriptconst s1 = "abc123xyz456"; const
2 min read
JavaScript Regular Expressions Coding Practice Problems
Regular expressions (regex) in JavaScript provide a powerful way to search, match, and manipulate text patterns. They are widely used in form validation, data extraction, text filtering, and pattern recognition. This curated list of regex-based coding problems is categorized into easy, medium, and h
1 min read