Extracting floats from strings
To get all float values from a sentence, we can first find them with a regular expression and then map over the matches with
// matches all integer or decimal substrings, like “69” or “4.20” const numbersRegexp = new RegExp(/\d+(\.\d+)?/, 'g') // finds all numbers matching the expression and transforms them to numbers const getFloatsFrom = string => string.match(numbersRegexp).map(parseFloat) getFloatsFrom("Put the 16 cupcakes in the oven (at 180°C) for 1.5 hours.") // ⇒ [16, 180, 1.5]
There is more to learn
Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.
Cannot show form because cookie consent was not given.