Search code examples
javascriptregexstringtypescriptfractions

How do I reliably find fractions and decimals in javascript


Q) I want to be able to parse a string in js and output the parts of the string that are either a number or a fraction.

e.g: "1.5 litres 1/4 cup"

Note: I've already figured out how to get the whole numbers and decimals from the example string below, but not the fraction representations.

I'm currently using something like this:

const originalString = "1.5 litres 1/4 cup";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
var match;

// FIX - does this ever actually get stuck ?
// replace this with non-while loop from article: http://danburzo.ro/string-extract/
while ((match = number_regex.exec(originalString)) !== null) {
  matches.push({
    original: match[0],
    newVal: ''
  });
}
console.log(matches)


Solution

  • You could use this to extract each number as an array of strings

    const input = `Take 1.5 litres 1/4 cup of sugar
        and 2ml or 2/3 teaspoon or salt
        then take 5 litres of 2.5% vinegar`
    
    const regex = /[+-]?\d+(?:[\.\/]?\d+)?/gm
    console.log(
      [...input.matchAll(regex)].map(a => a[0])
    )
    // returns ["1.5", "1/4", "2", "2/3", "5", "2.5"]