James
James

Reputation: 31778

How to get an array of numbers from a string in javascript

How would you get an array of numbers from a javascript string? Say I have the following:

var slop = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";

How could you get the following array:

nums = [3, 8, 4.2, 456];

Note: I'd like to not have to use jQuery if possible.

Upvotes: 1

Views: 56

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382464

You can do this :

var s = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";
var nums = s.split(/[^\d\.]+/).map(parseFloat)
    .filter(function(v){ return v===v });

Result : [3, 8, 4.2, 456]

Upvotes: 4

user1467267
user1467267

Reputation:

Basic regex fetching:

var string = 'I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456 hello.45';
var result = string.match(/((?:\d+\.?\d*)|(?:\.\d+))/g);
console.log(result);

Result:

["3", "8", "4.2", "456", ".45"]

Edit

Updated to work with non-prefixed 0.xx decimals. If that's not what you want, this was the old regex to match it as (ignore dot) full numeral:

var result = string.match(/(\d+\.?\d*)/g);

Old Result:

["3", "8", "4.2", "456", "45"]

Upvotes: 1

Related Questions