简体   繁体   中英

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.

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM