Parses a string, which can include mixed numbers or vulgar fractions (thanks to numeric-quantity), into an array of recipe ingredient objects.
Ingredient objects have the following signature:
interface Ingredient {
/**
* The primary quantity (the lower quantity in a range, if applicable)
*/
quantity: number | null;
/**
* The secondary quantity (the upper quantity in a range, or `null` if not applicable)
*/
quantity2: number | null;
/**
* The unit of measure identifier (see `unitsOfMeasure`)
*/
unitOfMeasureID: string | null;
/**
* The unit of measure
*/
unitOfMeasure: string | null;
/**
* The description
*/
description: string;
/**
* Whether the "ingredient" is actually a group header, e.g. "For icing:"
*/
isGroupHeader: boolean;
/**
* Metadata about the parsed ingredient line.
* Only included when the `includeMeta` option is `true`.
*/
meta?: IngredientMeta;
}
interface IngredientMeta {
/**
* The source text of the ingredient line before parsing.
*/
sourceText: string;
/**
* The zero-based index of the line (or array element) in the original input.
* Empty lines are not parsed, but they do consume an index.
*/
sourceIndex: number;
}
Quantities are always finite, non-negative numbers when present — never negative, never NaN, never Infinity. A leading '-' is treated as part of the description, not as a sign or a range separator, so '-2 cups sugar' yields quantity: null with the description intact. Likewise '1/0 cups sugar' yields quantity: null with the description intact, since a division by zero is not a usable measurement. quantity2 is only set when quantity is also set — a range with no lower bound is not a range.
For the isGroupHeader attribute to be true, the ingredient string must not start with a number, and must either start with 'For ' or end with ':'.
If present (i.e., not null), the unitOfMeasureID property corresponds to a key from the exported unitsOfMeasure object which defines short, plural, and other alternate versions of known units of measure. To extend the list of units, use the additionalUOMs option and/or or submit a pull request to add new units to this library's default list.
For a complimentary library that handles the inverse operation, displaying numeric values as imperial measurements (e.g.
'1 1/2'instead of1.5), see format-quantity.
npm i parse-ingredient
# OR yarn add / pnpm add / bun add
In the browser, all exports including the parseIngredient function are available on the global object ParseIngredient.
<script src="https://unpkg.com/parse-ingredient"></script>
<script>
ParseIngredient.parseIngredient('1 1/2 cups sugar');
// [
// {
// quantity: 1.5,
// quantity2: null,
// unitOfMeasure: 'cups',
// unitOfMeasureID: 'cup',
// description: 'sugar',
// isGroupHeader: false,
// }
// ]
</script>
The parseIngredient function accepts a string (with newline-separated ingredients) or an array of strings (one ingredient per element).
import { parseIngredient } from 'parse-ingredient';
parseIngredient('1-2 pears');
// [
// {
// quantity: 1,
// quantity2: 2,
// unitOfMeasure: null,
// unitOfMeasureID: null,
// description: 'pears',
// isGroupHeader: false,
// }
// ]
parseIngredient(
`2/3 cup flour
1 tsp baking powder`
);
// [
// {
// quantity: 0.667,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'flour',
// isGroupHeader: false,
// },
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'tsp',
// unitOfMeasureID: 'teaspoon',
// description: 'baking powder',
// isGroupHeader: false,
// },
// ]
parseIngredient('For cake:');
// [
// {
// quantity: null,
// quantity2: null,
// unitOfMeasure: null,
// unitOfMeasureID: null,
// description: 'For cake:',
// isGroupHeader: true,
// }
// ]
parseIngredient('Ripe tomato x2');
// [
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: null,
// unitOfMeasureID: null,
// description: 'Ripe tomato',
// isGroupHeader: false,
// }
// ]
normalizeUOMPass true to convert units of measure to their long, singular form, e.g. "ml" becomes "milliliter" and "cups" becomes "cup". This can help normalize the units of measure for processing. In most cases, this option will make unitOfMeasure equivalent to unitOfMeasureID.
parseIngredient('1 c sugar', { normalizeUOM: true });
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'sugar',
// isGroupHeader: false,
// }
// ]
additionalUOMsPass an object that matches the format of the exported unitsOfMeasure object. Keys that match any in the exported object will be used instead of the default, and any others will be added to the list of known units of measure when parsing ingredients.
parseIngredient('2 buckets of widgets', {
additionalUOMs: {
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: ['bk'],
type: 'volume',
},
},
});
// [
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasureID: 'bucket',
// unitOfMeasure: 'buckets',
// description: 'widgets',
// isGroupHeader: false,
// },
// ]
allowLeadingOfWhen true, ingredient descriptions that start with "of " will not be modified. (By default, a leading "of " will be removed from all descriptions.)
parseIngredient('1 cup of sugar', { allowLeadingOf: true });
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'of sugar',
// isGroupHeader: false,
// }
// ]
ignoreUOMsAn array of strings to ignore as units of measure when parsing ingredients.
parseIngredient('2 large eggs', { ignoreUOMs: ['large'] });
// [
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: null,
// unitOfMeasureID: null,
// description: 'large eggs',
// isGroupHeader: false,
// }
// ]
includeMetaWhen true, each ingredient object will include a meta property containing source metadata:
sourceText: The original text of the ingredient line before parsing.sourceIndex: The zero-based index of the line (or array element) in the original input. Empty lines are not parsed, but they do consume an index.parseIngredient('1 cup flour\n\n2 tbsp sugar', { includeMeta: true });
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'flour',
// isGroupHeader: false,
// meta: { sourceText: '1 cup flour', sourceIndex: 0 },
// },
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: 'tbsp',
// unitOfMeasureID: 'tablespoon',
// description: 'sugar',
// isGroupHeader: false,
// meta: { sourceText: '2 tbsp sugar', sourceIndex: 2 },
// },
// ]
roundRounds parsed quantities to the given number of decimal places, or disables rounding entirely when set to false. Defaults to 3.
parseIngredient('1 11/16 cups sugar');
// [{ quantity: 1.688, ... }]
parseIngredient('1 11/16 cups sugar', { round: false });
// [{ quantity: 1.6875, ... }]
parseIngredient('1 2/3 cups sugar', { round: 1 });
// [{ quantity: 1.7, ... }]
descriptionMeasurementsWhen true, each ingredient object will include a descriptionMeasurements array holding the quantity/unit pairs found within its description — the measurements the parser does not extract because they are not the ingredient's own amount.
parseIngredient('1 pound beef, cut into 1 1/2-inch cubes', {
descriptionMeasurements: true,
});
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasureID: 'pound',
// unitOfMeasure: 'pound',
// description: 'beef, cut into 1 1/2-inch cubes',
// isGroupHeader: false,
// descriptionMeasurements: [
// {
// quantity: 1.5,
// quantity2: null,
// unitOfMeasureID: 'inch',
// unitOfMeasure: 'inch',
// unitType: 'length',
// text: '1 1/2-inch',
// startIndex: 15,
// endIndex: 25,
// sourceStartIndex: 23,
// sourceEndIndex: 33,
// },
// ],
// },
// ]
startIndex and endIndex are indices into description and are always present; text is always exactly description.slice(startIndex, endIndex). sourceStartIndex and sourceEndIndex are the same span's position in the original line, which is what includeMeta reports as meta.sourceText. They are null in the rare cases where the description cannot be mapped back onto the line unambiguously; the description-relative indices remain valid regardless.
The description is scanned, not the line, so an ingredient's own quantity and unit are never reported twice:
parseIngredient('1 cup flour', { descriptionMeasurements: true });
// [{ description: 'flour', descriptionMeasurements: [], ... }]
Group headers are labels rather than measurements, so they always carry an empty array.
Note:
Cis a recognized abbreviation forcup, so text containing an oven temperature like'bake at 175 C'reports a 175-cup measurement. PassignoreUOMs: ['C', 'F']when scanning text that may contain temperatures.
measurementUnitsControls which units count as a description measurement. Has no effect unless descriptionMeasurements is true. Defaults to 'all'.
Note that piece, pinch, large, and the other count/other units are real units of measure, so by default "cut into 4 pieces" is a measurement. Use 'convertible' to see only the units convertUnit can act on — those with a conversionFactor.
parseIngredient('2 eggs, cut into 4 pieces', { descriptionMeasurements: true });
// [{ descriptionMeasurements: [{ quantity: 4, unitOfMeasureID: 'piece', ... }], ... }]
parseIngredient('2 eggs, cut into 4 pieces', {
descriptionMeasurements: true,
measurementUnits: 'convertible',
});
// [{ descriptionMeasurements: [], ... }]
Every measurement also carries the unit's unitType, so the results can be filtered without a second lookup.
The library supports parsing ingredients in multiple languages through configurable keyword options. While unit names can be localized using additionalUOMs, the following options allow localization of parsing keywords and quantities.
decimalSeparatorThe character used as a decimal separator in numeric quantities. Use ',' for European-style decimal commas (e.g., '1,5' for 1.5). Defaults to '.'.
parseIngredient('1,5 cups sugar', { decimalSeparator: ',' });
// [
// {
// quantity: 1.5,
// quantity2: null,
// unitOfMeasure: 'cups',
// unitOfMeasureID: 'cup',
// description: 'sugar',
// isGroupHeader: false,
// }
// ]
groupHeaderPatternsPatterns to identify group headers (e.g., "For the icing:"). Strings are treated as prefix patterns matched at the start of the line followed by whitespace. RegExp patterns are used as-is for more complex matching. Defaults to ['For'].
// German group headers
parseIngredient('Für den Teig:\n2 cups flour', {
groupHeaderPatterns: ['For', 'Für'],
});
// [
// { description: 'Für den Teig:', isGroupHeader: true, ... },
// { quantity: 2, unitOfMeasure: 'cups', description: 'flour', ... }
// ]
// French with regex pattern (matches "Pour la", "Pour le", "Pour un", etc.)
parseIngredient('Pour la pâte:', {
groupHeaderPatterns: ['For', /^Pour\s/iu],
});
rangeSeparatorsWords or patterns to identify ranges between quantities (e.g., "1 to 2", "1 or 2"). Dash characters (-, –, —) are always recognized. Defaults to ['to', 'or'].
// German range separators
parseIngredient('1 bis 2 cups flour', {
rangeSeparators: ['to', 'or', 'bis', 'oder'],
});
// [{ quantity: 1, quantity2: 2, ... }]
// French range separator
parseIngredient('2 à 3 cups sugar', {
rangeSeparators: ['to', 'or', 'à', 'ou'],
});
Note: RegExp separators are used as-is, except that named capture groups (
(?<name>…)) in them are rewritten as non-capturing groups so they can't collide with the library's own group names. Lookbehinds ((?<=…),(?<!…)) are unaffected. Plain capture groups are also safe, but their contents are not surfaced anywhere.
descriptionStripPrefixesWords or patterns to strip from the beginning of ingredient descriptions. Commonly used to remove "of" from phrases like "1 cup of sugar". Strings are matched as whole words followed by whitespace. RegExp patterns are used as-is, which is useful for languages with contractions or elisions. Defaults to ['of'].
Note: This option is only applied when
allowLeadingOfisfalse(the default). IfallowLeadingOfistrue, prefix stripping is disabled entirely and this option is ignored.Note: Prefixes are stripped from the description after the unit of measure has been extracted. If the unit is not recognized (i.e., not registered via
additionalUOMs), it remains at the start of the description and the prefix will not be at the start anymore, so nothing gets stripped. That is why both examples below also register the unit.
// Spanish "de" stripping
parseIngredient('2 tazas de azúcar', {
descriptionStripPrefixes: ['of', 'de'],
additionalUOMs: {
taza: { short: 'tz', plural: 'tazas', alternates: ['taza'] },
},
});
// [{ quantity: 2, unitOfMeasure: 'tazas', description: 'azúcar', ... }]
// French with regex patterns for elisions/contractions
parseIngredient("2 tasses d'huile", {
descriptionStripPrefixes: [/de\s+la\s+/iu, /de\s+l'/iu, /d'/iu, 'de'],
additionalUOMs: {
tasse: { short: 't', plural: 'tasses', alternates: ['tasse'] },
},
});
// [{ quantity: 2, unitOfMeasure: 'tasses', description: 'huile', ... }]
trailingQuantityContextWords that indicate a trailing quantity extraction context, used to identify patterns like "Juice of 3 lemons". Defaults to ['from', 'of'].
// German context word
parseIngredient('Saft von 3 Zitronen', {
trailingQuantityContext: ['from', 'of', 'von'],
});
// [{ quantity: 3, description: 'Saft von Zitronen', ... }]
leadingQuantityPrefixesWords or patterns to strip from the beginning of quantity expressions. Useful for approximation prefixes and modifiers like 'about', 'ca.', or 'bis zu'. Defaults to [].
Note: When providing multiple patterns, list longer/more-specific patterns before shorter ones. Standard regex alternation matches left-to-right, so
['ca', 'ca.']would match"ca"first in"ca. 200g", leaving". 200g". Use['ca.', 'ca']instead.Note: Be mindful of overlap between
rangeSeparatorsandleadingQuantityPrefixes. For example, withrangeSeparators: ['bis']andleadingQuantityPrefixes: ['bis zu'], input like"3 bis zu 5 EL"will match"bis"as a range separator first during range extraction, leaving"zu 5 EL". The prefix regex won't strip the leftover"zu"on its own. If you need both, ensure the range separator and prefix don't share a common leading word, or accept the range interpretation taking priority.
// English approximation prefix
parseIngredient('about 2 cups sugar', {
leadingQuantityPrefixes: ['about'],
});
// [{ quantity: 2, unitOfMeasure: 'cups', description: 'sugar', ... }]
// German prefixes
parseIngredient('ca. 200 g Mehl', {
leadingQuantityPrefixes: ['ca.'],
});
// [{ quantity: 200, unitOfMeasure: 'g', description: 'Mehl', ... }]
parseIngredient('bis zu 3 EL Zucker', {
rangeSeparators: ['to', 'or', 'bis'],
leadingQuantityPrefixes: ['bis zu'],
additionalUOMs: {
tablespoon_de: { short: 'EL', plural: 'EL', alternates: [] },
},
});
// [{ quantity: 3, unitOfMeasure: 'EL', description: 'Zucker', ... }]
parseIngredient(
`Für den Kuchen:
2 bis 3 Tassen Mehl
1 Tasse Zucker`,
{
groupHeaderPatterns: ['For', 'Für'],
rangeSeparators: ['to', 'or', 'bis', 'oder'],
decimalSeparator: ',',
additionalUOMs: {
tasse: {
short: 'T',
plural: 'Tassen',
alternates: ['Tasse'],
},
},
}
);
// [
// { description: 'Für den Kuchen:', isGroupHeader: true, ... },
// { quantity: 2, quantity2: 3, unitOfMeasure: 'Tassen', description: 'Mehl', ... },
// { quantity: 1, unitOfMeasure: 'Tasse', description: 'Zucker', ... }
// ]
partialUnitMatchingWhen true, if normal whitespace-based parsing fails to identify a unit of measure, the parser scans the description for known UOM strings registered via additionalUOMs. This is useful for CJK languages (Japanese, Chinese, Korean) where words are not separated by spaces.
parseIngredient('砂糖大さじ2', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: { short: '大さじ', plural: '大さじ', alternates: [] },
},
});
// [
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: '大さじ',
// unitOfMeasureID: '大さじ',
// description: '砂糖',
// isGroupHeader: false,
// }
// ]
The scan also works with Latin UOMs already known to the library (e.g., g, ml) and mixed-language ingredient lists:
parseIngredient('砂糖大さじ2\nバター10g\n1 cup flour', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: { short: '大さじ', plural: '大さじ', alternates: [] },
},
});
// [
// { quantity: 2, unitOfMeasure: '大さじ', description: '砂糖', ... },
// { quantity: 10, unitOfMeasure: 'g', description: 'バター', ... },
// { quantity: 1, unitOfMeasure: 'cup', description: 'flour', ... },
// ]
When multiple UOM strings could match, the longest match wins (e.g., 大さじ is preferred over 大).
convertUnitConverts a numeric value from one unit of measure to another. Accepts unit IDs, short forms, plurals, or alternate spellings (e.g., 'cup', 'c', 'cups', 'C'). Returns the converted value, or null if conversion is not possible (incompatible types, missing conversion factors, or unknown units).
import { convertUnit } from 'parse-ingredient';
convertUnit(1, 'cup', 'milliliter'); // ~236.588 (US)
convertUnit(1, 'cups', 'ml'); // ~236.588 (same as above)
convertUnit(1, 'pound', 'gram'); // ~453.592
convertUnit(1, 'lbs', 'g'); // ~453.592 (same as above)
convertUnit(1, 'inch', 'centimeter'); // ~2.54
convertUnit(1, 'cup', 'gram'); // null (incompatible types: volume vs mass)
fromSystem: The measurement system to use for the source unit ('us', 'imperial', or 'metric'). Defaults to 'us'.toSystem: The measurement system to use for the target unit. Defaults to 'us'.additionalUOMs: Additional unit definitions to use for conversion (merged with the default unitsOfMeasure).// Convert using different measurement systems
convertUnit(1, 'cup', 'milliliter', { fromSystem: 'imperial' }); // ~284.131
convertUnit(1, 'cup', 'cup', { fromSystem: 'us', toSystem: 'imperial' }); // ~0.833
// Use custom unit definitions
convertUnit(1, 'bucket', 'liter', {
additionalUOMs: {
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: [],
type: 'volume',
conversionFactor: 10000, // 10000 ml = 10 liters
},
},
}); // 10
conversionFactorThe conversionFactor property in unit definitions enables the convertUnit function. Units with the same type (e.g., 'volume', 'mass', 'length') can be converted between each other.
us, imperial, and/or metric systems.// Single factor (same for all systems)
gram: {
short: 'g',
plural: 'grams',
type: 'mass',
conversionFactor: 1, // base unit for mass
}
// Multi-system factors
cup: {
short: 'c',
plural: 'cups',
type: 'volume',
conversionFactor: { us: 236.588, imperial: 284.131, metric: 250 },
}
Supported unit types: volume, mass, length. Units without a conversionFactor or type (such as pinch, clove, or count-based units like bag) cannot be converted.
extractMeasurementsFinds every quantity paired with a known unit of measure in an arbitrary string, along with where each one sits in the text. This is exactly what the descriptionMeasurements option runs over each ingredient's description, exposed on its own for text that has already been parsed — a description, a recipe step, a note.
import { extractMeasurements } from 'parse-ingredient';
extractMeasurements('cut into 1 1/2-inch cubes');
// [
// {
// quantity: 1.5,
// quantity2: null,
// unitOfMeasureID: 'inch',
// unitOfMeasure: 'inch',
// unitType: 'length',
// text: '1 1/2-inch',
// startIndex: 9,
// endIndex: 19,
// },
// ]
Ranges are recognized the same way the parser recognizes them:
extractMeasurements('cut into 1 to 2 inch cubes');
// [{ quantity: 1, quantity2: 2, text: '1 to 2 inch', ... }]
A unit is only reported when the text immediately before it parses, in its entirety, as a quantity or a range. That is what keeps prose out of the results:
extractMeasurements('stir into the pan and add a pinch of salt');
// []
The unit IDs feed straight into convertUnit, which is the point:
convertUnit(extractMeasurements('cut into 1 1/2-inch cubes')[0].quantity, 'inch', 'cm'); // 3.81
extractMeasurements accepts the additionalUOMs, decimalSeparator, ignoreUOMs, measurementUnits, normalizeUOM, rangeSeparators, and round options, with the same meanings they have in parseIngredient.
Thanks goes to these wonderful people (emoji key):
Jake Boone 💻 📖 💡 🚧 ⚠️ |
Stefan van der Weide 💻 ⚠️ |
Roger 💻 |
Tyler 💻 ⚠️ |
AfoxDesignz 💻 ⚠️ |
Justin Williams 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!