In this article, we will learn how we can extract the numbers if exist in a given string.
Method to Extract Numbers from Given 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 myGeeks() {
let str = "jhkj7682834" ;
console.log(str)
let matches = str.match(/(\d+)/);
if (matches) {
console.log(matches[0]);
}
}
myGeeks();
|
Outputjhkj7682834
7682834
Example 2: This example uses the match() function to extract numbers from strings.
Javascript
function myGeeks() {
let str = "foo35bar5jhkj88" ;
console.log(str)
let matches = str.match(/\d+/g);
if (matches) {
console.log(matches[0] + ', ' + matches[1]+ ', ' + matches[2]);
}
}
myGeeks();
|
Outputfoo35bar5jhkj88
35, 5, 88
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.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: This example spread operator to convert into an array and the reduce method to extract all the numbers from the string.
Javascript
function myGeeks() {
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), "" );
if (matches) {
console.log(matches);
}
}
myGeeks();
|
Outputjhkj7682834
7682834
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.
Syntax:
str.replace(value1, value2)
Example: In this example, we will use the JavaScript replace() method with regEx to extract the numbers out of given string
Javascript
function myGeeks() {
let str = "jhkj7682834" ;
console.log(str);
let matches = str.replace(/[^0-9]/g, "" );
if (matches) {
console.log(matches);
}
}
myGeeks();
|
Outputjhkj7682834
7682834
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.