Learn to extract the numeric values present in a string in JavaScript! This guide explores various ways, including regular expressions, to extract the numbers from the string. And also a way remove the numbers from the string.
Way 1: Match method.
As the match method returns the matches.
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let output = "";
output = string.match(/[0-9]/g);
console.log(output);
// Output:
// (2) ['2', '4']
console.log(output.join(","));
// Output:
// 2,4
console.log(output.join(""));
// Output:
// 24
Way 2: Replace method with regular expression.
Through the replace method we’ll replace all string characters to blank or null (like this "a" to "") except numbers using regular expression /[^0-9]/ .
See below code.
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let array = string.split("");
let output = "";
output = string.replace(/[^0-9]/g, "");
console.log(output);
// Output:
// 24
Way 3: Using Split, Match method and For loop.
First we’ll split the string into a character and through a for loop we’ll check each character that it's a number or not through JavaScript match method with regular expression.
See the below code:
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let array = string.split("");
let output = "";
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (element.match(/[0-9]/g)) {
output += element;
}
}
console.log(output);
// Output:
// 24
There may be more ways to extract the numbers you can comment down below.
Remove the numeric value from the string.
In the above methods we just extract the numbers but the string still contains it. To remove the number from the strings you can simply replace it with null or "".
See below code.
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let output = string.replace(/[0-9]/g, "");
console.log(output);
// Output:
// Thanks you visiting maketechstuff.com
So it's easy to extract the numeric values present in a string using JavaScript. Feel free to write any doubt, questions and suggestions in the comment section.
You may like:
- How to remove the numeric values present in the string using JavaScript.
- How to detect the numeric values present in the string using JavaScript.
Share your thoughts.