In this article, we will explore how to extract a numeric value from a String using JavaScript.
We can only get those numbers that are present in the provided string. There are various methods by which we can get a number from String, which are as follows:
- JavaScript match method with regEx
- JavaScript reduce method with the spread operator
- JavaScript replace method with regEx
We will explore all the techniques to extract a number from a String in JavaScript, examining each method individually.
JavaScript match method with regEx
The match method allows us to extract a number from a string. This method requires a regular expression (regEx) as its argument. A regular expression is a sequence that specifies the format of a string, enabling the identification of various types of text, including email addresses, passwords, and more. It can also be employed for validation tasks, such as verifying the format of an email address.
Syntax:
let str = "example123456";
let numbers = str.match(/(\d+)/);
The method str.match is referenced in the syntax provided above. The expression (/(\d+)/) serves as the functional argument, representing the regular expression we will employ to extract numbers from a string. The metacharacter \d is used to identify digits within the range of 0 to 9.
Demonstration-1:
In the upcoming demonstration, we will be retrieving a numerical value from a specified string. To accomplish this, we will employ the match function to align the string with a regular expression, specifically (/(\d+)/), to identify the targeted number within the string.
Code:
function getNumbers() {
let str = "hello12345";
console.log(str)
let matches = str.match(/(\d+)/);
if (matches) {
console.log(matches[0]);
}
}
getNumbers();
Output:
Presented below is the output where we can observe a digit that has been retrieved from a string.
Demonstration-2:
We will extract all numeric values found within the specified string. To accomplish this, we will employ the match method in conjunction with the regular expression, namely, (/(\d+)/g), to identify the desired substring. The 'g' flag in the regex denotes a global search, allowing us to locate every instance of numbers that exist within the string.
Code:
function getNumbers() {
let str = "every12345 number678 9present in the string";
console.log(str)
let matches = str.match(/(\d+)/g);
if (matches) {
console.log(matches[0] +', '+ matches[1]+', ' + matches[2]);
}
}
getNumbers();
Output:
The results displayed below allow us to observe each individual number that has been extracted.
JavaScript reduce method with the spread operator
arr.reduce
The arr.reduce method is employed to condense an array into a single value.
Syntax:
arr.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
The function(total, currentValue, currentIndex, arr) and initialValue are the parameters that the arr.reduce function takes. They are described below:
- function(total, currentValue, currentIndex, arr): It is the function which takes 4 parameters described below: total: It is utilized to define the previously returned value or initial value. currentValue: It is utilized to define the current element's value. currentIndex: This parameter is optional and it is utilized to define the current element's array index. arr: This parameter is optional and it is utilized to define the array object to which the current element belongs.
- initialValue: This parameter is optional and it is utilized to define the initial value which is passed to the reduce method.
- total: It is utilized to define the previously returned value or initial value.
- currentValue: It is utilized to define the current element's value.
- currentIndex: This parameter is optional and it is utilized to define the current element's array index.
- arr: This parameter is optional and it is utilized to define the array object to which the current element belongs.
Spread operator
The spread operator (…) serves the purpose of duplicating an existing array into a new array. It extracts values from an array.
Syntax:
let array1 = [value1, value2, value3];
arr = [...arrary1];
Demo:
We will extract a numerical value from a specified string using the arr.reduce method in conjunction with the spread operator.
Code:
function myNum() {
let str = "get-the-number-01256";
let num = "0123456789";
console.log(str);
function check(a) {
return num.includes(a) ? true : false;
}
let matches = [...str].reduce(
(a, b) => (check(b) ? a + b : a),"");
if (matches) {
console.log(matches);
}
}
myNum();
Output:
In this example, we can observe the process of extracting a number from a string by employing the reduce function.
JavaScript replace method with regEx
The replace method serves the purpose of substituting a specified segment of the provided string with an alternative string. It is important to remember that the original string remains unchanged.
Syntax:
str.replace(value1, value2);
The parameters of the replace function are referred to as value1 and value2. Here, value1 represents the regular expression (regEx) that identifies the string pattern needing replacement, whereas value2 signifies the string that will substitute the specified portion of the original string.
Demonstration-1:
In this demonstration, we will create a JavaScript function that extracts a number from a string by employing the replace method in conjunction with regular expressions (regEx).
Code:
function myNum() {
let str = "findthenumber1010201";
console.log(str);
let matches = str.replace(/[^0-9]/g, "");
if (matches) {
console.log(matches);
}
}
myNum();
Output:
In the following output below, we can observe the extraction of a number from a string through the use of the replace function.
Demonstration-2:
In this demonstration, we will create a JavaScript application that extracts a decimal number from a given string by employing the replace method in conjunction with regular expressions (regEx).
Code:
function myNum() {
let str = "iPadOS 17.2 update";
console.log(str);
let matches = str.replace(/^\D+|\D+$/g, "");
if (matches) {
console.log(matches);
}
}
myNum();
Output:
In the output, we can distinctly observe a decimal number that has been extracted from a specified string using the replace method.
Conclusion:
We have grasped the concept of extracting a numerical value from a string using JavaScript. Through various examples, we have explored different techniques to retrieve a number from a string. The methods for obtaining a number include employing the JavaScript match function alongside regular expressions (regEx), utilizing the JavaScript reduce function in conjunction with the spread operator, and applying the JavaScript replace function along with regular expressions.