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.
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
Extract a number from a string using JavaScript
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.
These are the following methods by using these we can solve the problems:
Table of Content
- JavaScript reduce() method with the spread operator to extract a number from a string
- JavaScript replace() method with regEx to extract a number from a string
- JavaScript for loop to extract a number from a string
- Using Array.prototype.filter with split