The quantity string to parse (e.g., '100g', '120 grams')
Object containing quantity and UOM, or undefined if parsing fails
If the quantity string cannot be parsed
parseQuantity('100g') // Returns { quantity: 100, uom: 'g' }
parseQuantity('120 grams') // Returns { quantity: 120, uom: 'grams' }
parseQuantity('43.4 ounce') // Returns { quantity: 43.4, uom: 'ounce' }
parseQuantity('1200 milliliters') // Returns { quantity: 1200, uom: 'milliliters' }
parseQuantity('1.2 L') // Returns { quantity: 1.2, uom: 'L' }
parseQuantity('1.2 g/mol') // Returns nothing, as g/mol is not a quantity
export function parseQuantity(value: string): QuantityObject | void {
if (!value) return;
const quantityPatternRegex = new RegExp(quantityPattern, "i");
const quantityMatch = value.match(quantityPatternRegex);
if (!quantityMatch?.groups?.quantity || !quantityMatch?.groups?.uom) return;
let parsedQuantity: string | number = quantityMatch.groups.quantity;
// Handle foreign number formats where commas and decimals are swapped
if (parsedQuantity.match(/^(\d+\.\d+,\d{1,2}|\d{1,3},\d{1,2}|\d{1,3},\d{1,2})$/))
parsedQuantity = parsedQuantity
.replaceAll(".", "xx")
.replaceAll(",", ".")
.replaceAll("xx", ",");
const uom = standardizeUom(quantityMatch.groups.uom);
const quantity = parseFloat(parsedQuantity.replaceAll(/[,\s]/g, ""));
const multiplier = parseInt(quantityMatch.groups?.multiplier ?? "1");
if (uom && quantity) return normalizeQuantity({ quantity: quantity * multiplier, uom });
}
Parses a quantity string into a structured object containing the numeric value and unit of measure. Handles various formats including foreign number formats (e.g., 1.234,56). Uses regex pattern matching to extract quantity and unit information.