↩︎

paraphrase

String template interpolation

npm i -S paraphrase

Creates new paraphrase method instance

const paraphrase = require('paraphrase');
const phrase = paraphrase(/\${([^{}]*)}/gm); // Create a new phrase function using a RegExp match

phrase('Hello, ${name}', {name: 'Martin'}); // Hello, Martin

Acceptable replacements (values) are strings and numbers

Arguments and Options

One or more RegExp replacers, an optional options object at the end

option meaning type default
resolve Should resolve dot notations within the template Boolean true
clean Should remove unmatched template instances Boolean false
Multiple replacers
const phrase = paraphrase(/\${([^{}]*)}/gm, /\{{([^{}]*)}}/gm);

phrase('Hello, ${firstname} {{lastname}}', {firstname: 'Martin', 'lastname': 'Prince'}); // Hello, Martin Prince
Dot notation resolve

Treat dots as part of the key instead of notation marks

const phrase = paraphrase(/\${([^{}]*)}/gm, {resolve: false});

phrase('Hello, ${name} ${last.name}', {name: 'Martin', 'last.name': 'Prince'}); // Hello, Martin Prince
Unmatched cleanup

Remove unmatched template instances from the result string

const phrase = paraphrase(/\${([^{}]*)}/gm, {clean: true});

phrase('Hello, ${firstname} ${lastname}', {firstname: 'Martin'}); // Hello, Martin

Examples

Objects

phrase('Hello, ${name}', {name: 'Martin'}); // Hello, Martin

Objects with dot notation

const user = {
    name: {first: 'Martin', last: 'Prince'}
};
phrase('Hello, ${name.first} ${name.last}', user); // Hello, Martin Prince

Arrays

phrase('Hello, ${0} ${1}', ['Martin', 'Prince']); // Hello, Martin Prince

Spread arguments

phrase('Hello, ${0} ${1}', 'Martin', 'Prince'); // Hello, Martin Prince

Premade

dollar ${...}

const phrase = require('paraphrase/dollar');

phrase('Hello, ${name}', {name: 'Martin'}); // Hello, Martin

double {{...}}

const phrase = require('paraphrase/double');

phrase('Hello, {{name}}', {name: 'Martin'}); // Hello, Martin

single {...}

const phrase = require('paraphrase/single');

phrase('Hello, {name}', {name: 'Martin'}); // Hello, Martin

percent %{...} (i18n style)

const phrase = require('paraphrase/percent');

phrase('Hello, %{name}', {name: 'Martin'}); // Hello, Martin

hash #{...} (ruby style)

const phrase = require('paraphrase/hash');

phrase('Hello, #{name}', {name: 'Martin'}); // Hello, Martin

patterns

A paraphrase instance exposes access to it's patterns array

const phrase = require('paraphrase/hash');

phrase.patterns // [ /#{([^{}]*)}/gm ]

Bundled version

Environments which exclude node_modules from the transpiling pipeline should include the "browser" entry instead of "main". This exposes a bundled ES5 commonjs module.

Also available for explicit import:

const paraphrase = require('paraphrase/dist');