Open In App

Extract a number from a string using JavaScript

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how we can extract the numbers if 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.

Extract a number from a string using JavaScript

These are the following methods by using these we can solve the problems:

JavaScript match method with regEx to extract a number from a string

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. The regular expression for extracting a number is (/(\d+)/). 

Example 1: This example uses the match() function to extract numbers from strings with regular expressions. 

Javascript
// Function to extract numbers
function myGeeks() {

    // Input string
    let str = "jhkj7682834";
    console.log(str)

    // Using match with regEx
    let matches = str.match(/(\d+)/);
    
    // Display output if number extracted
    if (matches) {
        console.log(matches[0]);
    }
}

// Function call
myGeeks();

Output
jhkj7682834
7682834

Example 2: This example uses the match() function to extract numbers from strings. 

Javascript
// Function to extract numbers
function myGeeks() {

    // Input string
    let str = "foo35bar5jhkj88";
    console.log(str)

    // Using match with regEx
    let matches = str.match(/\d+/g);
    
    // Display output if number extracted
    if (matches) {
        console.log(matches[0] +', '+ matches[1]+', ' + matches[2]);
    }
}

// Function call
myGeeks();

Output
foo35bar5jhkj88
35, 5, 88

JavaScript reduce() method with the spread operator to extract a number from a string

The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Example: This example spread operator to convert into an array and the reduce method to extract all the numbers from the string.

Javascript
// Function to extract numbers
function myGeeks() {
    // Input string
    let str = "jhkj7682834";
    let c = "0123456789";
    console.log(str);
    function check(x) {
        return c.includes(x) ? true : false;
    }
    let matches = [...str].reduce(
        (x, y) => (check(y) ? x + y : x),"");

    // Display output if number extracted
    if (matches) {
        console.log(matches);
    }
}

// Function call
myGeeks();

Output
jhkj7682834
7682834

JavaScript replace() method with regEx to extract a number from a string

The string.replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.

Example: In this example, we will use the JavaScript replace() method with regEx to extract the numbers out of given string

Javascript
// Function to extract numbers
function myGeeks() {
    // Input string
    let str = "jhkj7682834";
    console.log(str);

    // Using match with regEx
    let matches = str.replace(/[^0-9]/g, "");

    // Display output if number extracted
    if (matches) {
        console.log(matches);
    }
}

// Function call
myGeeks();

Output
jhkj7682834
7682834

JavaScript for loop to extract a number from a string

This approach loops through each character in the string and checks if it’s a number using isNaN(). If the character is a number, it appends it to numberStr.

Example: This example use for loop to extract all numbers present in the string.

Javascript
function extractNumbers(str) {
    let numbers = "";
    for (let i = 0; i < str.length; i++) {
        if (!isNaN(str[i])) {
            numbers += str[i];
        }
    }
    console.log(numbers)
}

// Input string
let str = "jhkj7682834hhdg237";
console.log(str);
extractNumbers(str);

Output
jhkj7682834hhdg237
7682834237


JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Previous Article
Next Article

Similar Reads

How to extract date from a string in dd-mmm-yyyy format in JavaScript ?
In this article, we will see how to extract date from a given string of format "dd-mmm-yyyy" in JavaScript. We have a string, and we want to extract the date format "dd-mmm-yyyy" from the string. Example: // String str = "India got freedom on 15-Aug-1947" // Extracted date from given string in // "dd-mmm-yyyy" format date = 15-Aug-1947 Approach: Th
2 min read
How to Extract URLs from a String in JavaScript ?
In this article, we are given a string str which consists of a hyperlink or URL present in it. We need to extract the URL from the string using JavaScript. The URL must be complete and you need to print the entire URL. Example: Input :-str = "Platform for geeks: https://www.geeksforgeeks.org"Output :-https://www.geeksforgeeks.orgExplanation: In the
2 min read
JavaScript Program to Extract First Word from a String
In this article, we have to extract the first word from the input string in JavaScript language. Below is an example for better understanding. Examples: Input: Geeks for Geeks Output: Geeks Input: I Love India Output: I Examples of Extracting First Word from a StringTable of Content Using split() MethodUsing substring() and indexOf() MethodsUsing R
4 min read
JavaScript Program to Extract Email Addresses from a String
In this article, we will explore how to extract email addresses from a string in JavaScript. Extracting email addresses from a given text can be useful for processing and organizing contact information. There are various approaches to extract email addresses from a string in JavaScript: Table of Content Using Regular ExpressionsSplitting and Filter
2 min read
How to extract the host name from URL using JavaScript ?
To extract the hostname portion from a URL, we can use the location object that represents information about the current URL. It is the element of the window object and a client-side object. Syntax: window.location.propertyname Example 1: In this example, we will use the self URL, where the code will run to extract the hostname. C/C++ Code &lt;!DOC
1 min read
JavaScript Program to Extract Strings that contain Digit
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 s
3 min read
JavaScript Program to Extract the Leftmost Set Bit of a Given Integer
We are given an integer value the task is to extract the leftmost set bit of a given integer in JavaScript. The leftmost set bit is a bit whose value is 1 and is present at the leftmost position in binary representation. The below approaches can be implemented to extract the leftmost set bit. Table of Content Using Bitwise OperationsUsing Logarithm
2 min read
JavaScript Program to Extract the Rightmost set Bit of a Given Integer
We are given an integer value, the task is to extract the rightmost set bit of a given integer in JavaScript. The rightmost set bit is the bit whose value is 1 and appears first when reading the binary representation of a number from right to left. The below approaches can be used to find the rightmost set bit in JavaScript. Table of Content Using
3 min read
How to extract numbers from string in PHP ?
In this article, we will extract numbers from strings using PHP. There are various built-in methods to extract numbers from strings, some of them are discussed below. Methods: Using preg_match_all() Function.Using filter_var() Function.Using preg_replace() function. Method 1: Using preg_match_all() Function. Note: preg_match() function is used to e
3 min read
How to extract Numbers From a String in PHP ?
The purpose of this article is to extract numbers from a string using PHP. Approach: We can use the preg_replace() function for the extraction of numbers from the string. /[^0-9]/ pattern is used for finding number as integer in the string (Refer to Example 1) /[^0-9\.]/ pattern is used for finding number as double in the string (Refer to Example 2
1 min read