1

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.

2 Answers 2

4

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]

Sign up to request clarification or add additional context in comments.

Comments

1

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.