how to find number in string js

How to Find Numbers in a String in JS

As a web developer, I often come across a situation where I need to extract numbers from a given string. In JavaScript, we can easily achieve this using regular expressions.

Method 1: Using Regular Expressions

Regular expressions are a powerful tool in JavaScript that help us search and manipulate strings. We can use the match() method along with a regular expression to extract numbers from a string.


let string = "I have 10 apples and 5 oranges";
let numbers = string.match(/\d+/g);
console.log(numbers);
// Output: [10, 5]

In the above code, we have defined a regular expression /\d+/g which matches all digits in the string. The match() method returns an array of all matches found in the string.

Method 2: Using Split Method

We can also use the split() method to split the string into an array of substrings based on a specified separator. In this case, our separator will be any character that is not a number.


let string = "I have 10 apples and 5 oranges";
let numbers = string.split(/[^\d]/).filter(Boolean);
console.log(numbers);
// Output: [10, 5]

In the above code, we have used a regular expression /[^\d]/ which matches any character that is not a digit. The split() method returns an array of substrings by splitting the original string based on the separator. We have used the filter() method to remove any empty elements from the array.

Method 3: Using Replace Method

We can also use the replace() method to replace all non-digit characters in the string with a separator of our choice. We can then use the split() method to split the string into an array of substrings based on the separator.


let string = "I have 10 apples and 5 oranges";
let numbers = string.replace(/[^\d]/g, ',').split(',');
console.log(numbers);
// Output: [10, 5]

In the above code, we have used a regular expression /[^\d]/g which matches any character that is not a digit. The replace() method replaces all matches found in the string with a comma. We can then use the split() method to split the string into an array of substrings based on the comma separator.

These are some of the ways we can find numbers in a string using JavaScript. Regular expressions provide a flexible and powerful way to search and manipulate strings in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe