A tool to extract key-value pairs by comparing (diffing) a template with an input string.
npm install flowxo/diffex
diffex
is initialised with a template, which is used as a base for the diffing.
A template is a simple string with {{placeholder}}
values. These placeholders will be replaced with data when the template is applied to an input string.
You should define your template variables inside {{
and }}
curly braces. Don't include any spaces inside the curlys, as this will prevent the extractor from working correctly.
For example, these template variables are ok:
{{name}}
{{first_name}}
{{last-name}}
whereas these are invalid:
{{ name }}
{{first name}}
{{ last name }}
Create the diffex object like so:
var do = diffex(template);
Once you have the diffex object, there are two methods available: placeholders()
and parse(input)
.
Parses the template and outputs all found placeholders.
Example:
var diffex = require('diffex');
var template = '{{customer}} owes £{{amount}}.';
diffex(template).placeholders();
// -> ['customer', 'amount']
Compares the template with an input, extracting the differences and outputting as key-value pairs.
var diffex = require('diffex');
var template = '{{customer}} owes £{{amount}}.';
var input = 'Bob owes £19.'
diffex(template).parse(input);
// -> { customer: 'Bob', amount: '19' }
The core diff algorithm was implemented by Neil Fraser, originally found here. The library is reproduced here under the Apache 2.0 license.
Apache 2.0