Natural language parser for recipe ingredients with multi-language support. Parses ingredient strings into structured objects and can combine multiple ingredient objects.
This project was built on top of code written by nsafai.
- Multi-language support: 13 languages including English, German, Italian, Spanish, French, Portuguese, Russian, Hindi, Indonesian, Arabic, Hungarian, Czech, and Dutch
- No external NLP libraries: Lightweight and fast
- Cross-platform: Works with Node.js, browser, and React Native
- Smart parsing: Handles fractions (including Unicode), ranges, and numbers written as words
- Unit system detection: Automatically classifies ingredients by measurement system (metric, imperial, US volumetric)
- Alternative measurements: Extracts alternative units and ingredient substitutions (parenthetical, slash-separated, "or" alternatives)
- Flexible input: Supports prepositions and natural language variations
npm install recipe-ingredient-parser-v3or
yarn add recipe-ingredient-parser-v3import { parse } from 'recipe-ingredient-parser-v3';
// English
parse('1 teaspoon basil', 'eng');
// Italian
parse('1 grammo di zucchero', 'ita');
// German
parse('2 Esslöffel Olivenöl', 'deu');Parses a single ingredient string into a structured object.
Parameters:
ingredientString(string): The ingredient text to parselanguage(string): Language code (see Languages Supported)options(object, optional):includeUnitSystems(boolean): IncludeunitSystemin output (default: false)includeAlternatives(boolean): Parse alternative measurements/ingredients (default: false)
Returns: Ingredient object with the following structure:
{
quantity: number, // Numeric quantity (average if range)
unit: string, // Canonical unit name (e.g., 'teaspoon', 'gram')
ingredient: string, // Name of the ingredient
minQty: number, // Minimum quantity (same as quantity if not a range)
maxQty: number, // Maximum quantity (same as quantity if not a range)
unitSystem: string, // Only if includeUnitSystems=true: 'metric', 'imperial', 'americanVolumetric', or null
preparation: string, // Preparation instructions (e.g., 'chopped', 'diced')
alternatives: array // Only if includeAlternatives=true: Alternative measurements/ingredients
}Example:
parse('2-3 cups diced tomatoes', 'eng', { includeUnitSystems: true });
// Returns:
{
quantity: 2.5,
unit: 'cup',
ingredient: 'tomatoes',
minQty: 2,
maxQty: 3,
unitSystem: 'americanVolumetric',
preparation: 'diced'
}Combines multiple ingredient objects with the same unit and ingredient name.
Parameters:
ingredientArray(array): Array of ingredient objects fromparse()
Returns: Array of combined ingredient objects
Example:
import { combine } from 'recipe-ingredient-parser-v3';
combine([
{
quantity: 1,
unit: 'teaspoon',
ingredient: 'basil',
minQty: 1,
maxQty: 2,
},
{
quantity: 2,
unit: 'teaspoon',
ingredient: 'basil',
minQty: 2,
maxQty: 2
}
]);
// Returns:
[{
quantity: 3,
unit: 'teaspoon',
ingredient: 'basil',
minQty: 3,
maxQty: 4
}]| Language | Code | Units | Example |
|---|---|---|---|
| English | eng |
52 | 1 cup flour |
| German | deu |
34 | 1 Tasse Mehl |
| Spanish | esp |
42 | 1 taza de harina |
| Italian | ita |
35 | 1 tazza di farina |
| French | fra |
42 | 1 tasse de farine |
| Portuguese | por |
42 | 1 xícara de farinha |
| Russian | rus |
41 | 1 чашка муки |
| Hindi | hin |
42 | 1 कप आटा |
| Indonesian | ind |
43 | 1 cangkir tepung |
| Arabic | ara |
42 | 1 فنجان دقيق |
| Hungarian | hun |
42 | 1 csésze liszt |
| Czech | ces |
42 | 1 hrnek mouky |
| Dutch | nld |
42 | 1 kopje bloem |
Want to add a new language? See Adding a New Language below.
The parser handles both ASCII and Unicode fractions:
parse('1/2 cup sugar', 'eng'); // quantity: 0.5
parse('1½ cups flour', 'eng'); // quantity: 1.5
parse('2 ¾ teaspoons salt', 'eng'); // quantity: 2.75Ingredient ranges are parsed with min/max quantities:
parse('2-3 tablespoons butter', 'eng');
// { quantity: 2.5, minQty: 2, maxQty: 3, ... }Numbers can be written as words:
parse('six cups milk', 'eng');
// { quantity: 6, unit: 'cup', ingredient: 'milk', ... }
parse('drei Esslöffel Öl', 'deu');
// { quantity: 3, unit: 'Esslöffel', ... }Handles natural language with prepositions:
parse('6 cups of milk', 'eng'); // English
parse('6 tazze di latte', 'ita'); // Italian
parse('6 Tassen von Milch', 'deu'); // GermanWhen includeUnitSystems: true, the parser classifies units:
metric: grams, kilograms, milliliters, liters, etc.imperial: ounces, pounds, fluid ounces, pints, gallonsamericanVolumetric: cups, quartsnull: System-agnostic (teaspoon, tablespoon) or count-based units (pieces, cloves)
parse('100 grams flour', 'eng', { includeUnitSystems: true });
// { ..., unitSystem: 'metric' }
parse('2 teaspoons salt', 'eng', { includeUnitSystems: true });
// { ..., unitSystem: null } // teaspoons are system-agnosticWhen includeAlternatives: true, the parser extracts alternative measurements or ingredients. This is useful for recipes that provide metric and imperial measurements, or offer ingredient substitutions.
Supported formats:
Alternative units in parentheses or brackets:
parse('450g (1 lb) of tinned tomatoes', 'eng', {
includeAlternatives: true,
includeUnitSystems: true
});
// Returns:
{
quantity: 450,
unit: 'gram',
unitSystem: 'metric',
ingredient: 'tinned tomatoes',
alternatives: [
{
quantity: 1,
unit: 'pound',
unitSystem: 'imperial',
ingredient: null,
minQty: 1,
maxQty: 1
}
]
}Alternative measurements separated by slashes:
parse('1 cup / 250ml milk', 'eng', { includeAlternatives: true });
// Returns:
{
quantity: 1,
unit: 'cup',
ingredient: 'milk',
alternatives: [
{
quantity: 250,
unit: 'milliliter',
ingredient: null
}
]
}Ingredient or measurement substitutions using "or":
parse('1 cup flour or 2 cups sugar', 'eng', { includeAlternatives: true });
// Returns:
{
quantity: 1,
unit: 'cup',
ingredient: 'flour',
alternatives: [
{
quantity: 2,
unit: 'cup',
ingredient: 'sugar',
minQty: 2,
maxQty: 2
}
]
}Alternative object structure:
Each alternative has the same structure as the main ingredient:
{
quantity: number,
unit: string,
unitPlural: string,
symbol: string,
ingredient: string, // null if only alternative unit, not ingredient
minQty: number,
maxQty: number,
originalString: string,
unitSystem: string // Only if includeUnitSystems=true
}The parser uses a centralized architecture:
src/i18n/index.js: Single source of truth for unit metadata (conversion factors, systems, decimal places)src/i18n/lang.*.js: Language-specific translations (unit names, singular/plural forms, symbols, linguistic data)- Runtime merging: Metadata + translations combined at import time
To add support for a new language:
Create src/i18n/lang.XXX.js (where XXX is the ISO 639-3 code):
export const unitTranslations = {
// For each unit in baseUnitsData (src/i18n/index.js):
gram: {
names: ['gram', 'grams', 'g', 'g.'], // All recognized variants
singular: 'gram', // Must match the unit key
plural: 'grams', // Plural form for display
symbol: 'g', // Symbol/abbreviation
},
// ... add all other units
};
const prepositions = ['of', 'with']; // Language-specific prepositions
const joiners = ['to', 'or']; // Range connectors
const toTaste = ['to taste']; // "To taste" variations
const toTasteAdditional = ['more', 'adjust'];
const additionalStopwords = ['and', 'or'];
const approx = ['about', 'approximately', '~'];
const optional = ['optional', 'if desired'];
const toServe = ['to serve', 'for serving'];
const badgeLabels = {
approx: { short: '~', label: 'approx', title: 'Approximate' },
optional: { short: 'opt', label: 'optional', title: 'Optional' },
toServe: { short: 'srv', label: 'to serve', title: 'To serve' },
toTaste: { short: 'tt', label: 'to taste', title: 'To taste' },
};
const languageName = 'English';
const instructions = [
'chopped', 'diced', 'sliced', 'minced',
// ... preparation instructions
];
const adverbs = ['finely', 'coarsely', 'thinly'];
const numbersSmall = {
zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5,
six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
// ... up to 90
};
const numbersMagnitude = {
hundred: 100,
thousand: 1000,
million: 1000000,
// ...
};
const problematicUnits = {
clove: ['garlic'], // Context clues for ambiguous units
};
// Optional: nutrition localization used by Vanilla Cookbook.
// Omit this block if English nutrition fallback is acceptable.
const nutrition = {
nutrientAliasExtras: {
calories: ['calories'],
carbohydrates: ['carbs'],
},
perServingPhrases: ['per serving', 'serving:'],
ignoreTokenExtras: ['nutrition facts'],
extraUnitAliasExtras: {
kcal: ['calorie', 'calories'],
},
};
export const langXXX = {
unitTranslations,
badgeLabels,
nutrition, // Optional
languageName,
prepositions,
joiners,
toTaste,
toTasteAdditional,
additionalStopwords,
approx,
optional,
toServe,
instructions,
adverbs,
numbersSmall,
numbersMagnitude,
problematicUnits,
isCommaDelimited: false, // Set true if language uses commas for decimals
};Add your language to src/i18n/index.js:
import {langXXX} from './lang.XXX.js';
// Add to languages:
const languages = {
eng: langEng,
deu: langDeu,
// ... other languages
XXX: langXXX, // Add your language
};nutrition configuration is optional and only needed if you want language-specific nutrition parsing aliases/phrases. If omitted, nutrition parsing falls back to shared defaults/English behavior.
You don't need to translate all 52 units immediately - start with common ones:
Essential units (minimum for basic functionality):
- Volume: teaspoon, tablespoon, cup, milliliter, liter
- Weight: gram, kilogram, ounce, pound
- Count: piece, clove, pinch
Reference: Check src/i18n/lang.eng.js for the complete list of units.
Note on pluralization: Some languages (Czech, Polish, Russian, Arabic) have complex plural rules with more than two forms (e.g., one/few/many). For parsing purposes, simply add all plural variants to the names array - the parser will recognize any form. For output display, use the most common plural form in the plural field.
Create test cases in test/:
import { parse } from '../src/index.js';
describe('Language XXX parsing', () => {
it('should parse basic ingredient', () => {
const result = parse('1 [translated unit] [ingredient]', 'XXX');
expect(result.quantity).toBe(1);
expect(result.unit).toBe('[canonical unit name]');
expect(result.ingredient).toBe('[ingredient]');
});
});All units are defined in baseUnitsData (src/i18n/index.js) with:
system:'metric','imperial','americanVolumetric', ornull- Set to
nullfor system-agnostic units (teaspoon, tablespoon) or count-based units
- Set to
unitType:'volume','weight','count','length'conversionFactor: Conversion to base units (e.g.,{ milliliters: 4.92 }for teaspoon)skipConversion:truefor units that shouldn't be converted (very small or count-based)decimalPlaces: Precision for conversions
- prepositions: Words that connect quantity/unit to ingredient ("of", "de", "di")
- joiners: Words for ranges ("to", "or", "bis", "à")
- instructions: Preparation methods (chopped, diced, etc.) - these are stripped from ingredient name
- problematicUnits: Units that need context (e.g., "clove" only with "garlic")
git clone https://github.com/jt196/recipe-ingredient-parser.git
cd recipe-ingredient-parser
npm installnpm test # Run all tests
npm run test:watch # Watch modenpm run build # Compile TypeScript to lib/
npm run build:test # Compile tests to testDist/
npm run watch # Watch mode for developmentnpm run lint # Check linting
npm run fmt # Format and fix linting issues
npm run test:ci # Lint + test (pre-publish)Checkout npm publishing docs for more info.
The prepublish hook automatically runs npm run build to refresh lib/ before publishing.
We welcome contributions! Here's how you can help:
This is the most impactful contribution. See Adding a New Language for detailed instructions. In summary:
- Copy
src/i18n/lang.eng.jsas a template - Translate unit names, adding all variants (abbreviations, plurals) to the
namesarray - Translate linguistic data (prepositions, instructions, number words)
- Register your language in
src/i18n/index.js - Add tests and submit a PR
Tip: Start with essential units (teaspoon, tablespoon, cup, gram, kilogram) and expand from there.
- Add missing unit translations
- Add more name variants for better recognition
- Expand instruction/preparation word lists
- Fix parsing issues for specific ingredient patterns
When reporting parsing issues, please include:
- The exact ingredient string that failed
- The language code used
- Expected vs actual output
MIT
- Original parser by nsafai
- Multi-language support and architecture improvements by contributors