Hello JavaScript developers, if you want to extract number from string in JavaScript, this article is for you. In this article, we will cover various methods that help to extract numbers from a string.
So without wasting time let’s start the article.
nowadays JavaScript is become an allrounder programming language. I am telling you this because you can use JavaScript everywhere, whether you want to create a Beautiful Website, Mobile Apps, Desktop Apps, Machine Learning, Backend, etc.
When working on the string data in JavaScript, sometimes you need to extract specific information, such as numbers from the string.
How many ways to Extract a number from a string in JavaScript?
Extracting the numbers can be a common task for example you need to validate the user input data.
There are 6 common methods to Extract numbers from the string in javascript.
- Method 1: Using Regular Expressions
- Method 2: Extraction of the First Number
- Method 3: Iterating Through Characters
- Method 4: Splitting the String
- Method 5: Using parseInt and Regular Expressions
- Methos 6: Using String Replace Method and Regular Expressions
Method 1: Extract number from String using Regular Expressions
Regular Expression allows us to write the pattern for matching the substring within the string. We can use them to match the numeric substring within the string.
Example:
let stringWithNumbers = "I have 12 mobiles and my age is 26"; let extractedNumbers = stringWithNumbers.match(/\d+/g).map(Number); console.log(extractedNumbers); // Output: [12, 26]
Code Explanation:
- “\d+” is a regular expression pattern for matching one or more digits.
- The “.match()” method helped to find all occurrences of the given pattern in the string.
- “map(Number)” is helped to convert the array of matched strings to an array of numbers.
Method 2: Extracting the first number from the String
If you want to extract only the first number from the string, we can use the same above code with some modifications.
Example:
let stringWithNumbers = "I have 12 mobiles and my age is 26"; let extractedNumbers = stringWithNumbers.match(/\d+/g).map(Number); let firstNumber = extractedNumbers ? Number(extractedNumbers[0]) : null; console.log(firstNumber); // Output: 12
Explanation :
- “match()” returns the array that contains the matched string or null if no match is found.
- If any match is found, we convert the matched substring to a number using Number()
Method 3: Iterating Through Characters
This is the simple method to Extract the number from a string by iterating through each character in the string and building the numbers.
Example:
function extractNumbersFromString(inputString) { let numberBuffer = ''; const numbers = []; for (let char of inputString) { if (!isNaN(char)) { numberBuffer += char; } else if (numberBuffer !== '') { numbers.push(Number(numberBuffer)); numberBuffer = ''; } } if (numberBuffer !== '') { numbers.push(Number(numberBuffer)); } return numbers; } // Example usage: let stringWithNumbers = "Hi i have 100 mobiles and 230 laptops"; let extractedNumbers = extractNumbersFromString(stringWithNumbers); console.log(extractedNumbers); // Output: [100, 230]
Explanation :
- We iterate through each character in the input string.
- We check each character as a digit, it appends to a buffer string.
- If the character is not a digit and the buffer string is not empty, we convert the buffer string to a number and push it to the result array.
Method 4: Extract the number by Splitting the String in JavaScript.
We can extract the number by splitting the string based on non-digit characters and filtering out non-numeric substrings.
Example :
let stringWithNumbers = "There are 123 apples and 456 oranges in the basket."; let extractedNumbers = stringWithNumbers.split(/\D+/).filter(Boolean).map(Number); console.log(extractedNumbers); // Output: [123, 456]
Code Explanation :
- First, we split the string into an array of substrings using the regex pattern that matches the non-digit character.
- We filter out non-numeric substrings using “filter(Boolean)” and convert them to numbers using “map(Number)”
Method 5: Extract the number by Using parseInt and Regular expressions JavaScript.
We can extract numbers by using the combination of parseInt with regular expressions.
Example :
let stringWithNumbers = "There are 123 apples and 456 oranges in the basket."; let firstNumber = parseInt(stringWithNumbers.match(/\d+/)[0]); console.log(firstNumber); // Output: 123
Code Explanation :
- We use parseInt() to convert the matched substring to a number.
Method 6: Extract the number by Using replace and Regular expressions JavaScript.
We can use String.replace() with a regex pattern to remove non-numeric characters from a string.
Example :
let stringWithNumbers = "There are 123 apples and 456 oranges in the basket."; let extractedNumbers = stringWithNumbers.replace(/\D+/g, ' ').trim().split(' ').map(Number); console.log(extractedNumbers); // Output: [123, 456]
Code Explanation :
- We replace all non-numeric characters with space using a regex pattern.
- Then split the resulting string into an array of substrings at each space and convert them to numbers.
Summary and Conclusion:
In summary, this article (Extract Number from String in JavaScript) explored the 6 methods to Extract numbers from String in JavaScript.
We can extract the numbers by using Regular Expressions, Iterating Through Characters, Splitting the String, parseInt() with Regular Expressions, and replace() with Regular Expressions.
I hope you have enjoyed this article if Yes, you can share it with your college friends and juniors.
Thank You!
(FAQs) About Extract Number from String in JavaScript
1) How to extract numbers from string JavaScript?
There are 6 common methods to Extract numbers from the string in javascript.
- By Using Regular Expressions
- By Extraction of the First Number
- By Iterating Through Characters
- Using Splitting the String
- Using parseInt and Regular Expressions
- Using String Replace Method and Regular Expressions
2) How do I extract only numbers from a string?
You can extract only numbers from string using the combination of parseInt, replace, and regular expressions.
3) How to extract value from a string in JavaScript?
you can extract value from string by using the given methods.
- Extracting a Substring
- Extracting Using Delimiters
- Extracting Numeric Values
- Parsing JSON