Tags
Asked 2 years ago
16 Jun 2021
Views 295
Adrien

Adrien posted

Return only numbers from string in JavaScript

Return only numbers from string in JavaScript
ruby-rails

ruby-rails
answered Apr 27 '23 00:00

To return only numbers from a string in JavaScript, you can use regular expressions and the match() method.

Here's an example:



const str = "abc 123 def 456 ghi 789";
const numbers = str.match(/\d+/g);
console.log(numbers); // Output: ["123", "456", "789"]

In this example, the regular expression /\d+/g matches one or more digits (\d+) globally (g) in the string. The match () method returns an array of all the matches, which we assign to the numbers variable.

If you want to convert the resulting array of strings to an array of numbers, you can use the map() method with the Number() constructor like this:



const str = "abc 123 def 456 ghi 789";
const numbers = str.match(/\d+/g).map(Number);
console.log(numbers); // Output: [123, 456, 789]

In this example, we chain the map () method after match () to convert each string in the resulting array to a number using the Number () constructor.
Post Answer