Hokey Cokey! Simple string template rendering and parameter value extracting
Hokey Cokey is a quick tool for extracting parameters from, and inserting parameters into, template strings:
Extract:
- Match a target string against a template e.g.
places/france/paris
and places/:country/{city}
- Return an object listing found values e.g.
{ country: "france", city: "paris" }
Render:
- Take a template string and merge in some values e.g.
places/${country}/:city
and { country: "france", city: "paris" }
- Return the rendered string after variables have been inserted e.g.
places/france/paris
Things to know:
- Works with parameters in
:express
, {jsx}
, {{handlebars}}
or ${es6}
format. - Doesn't do anything complicated (like RegExp patterns,
*
glob patterns, or optional parameters). - Parameter names must match the simple format
[a-zA-Z][a-zA-Z0-9]
. - When extracting values the template must have one character between each template parameter.
- Template destructuring is cached internally for performance.
- Well unit-tested and 100% covered.
- Useful for cases where RegExps are too fussy and you want something chunky and robust.
Installation
npm install hokey-cokey
Usage
Extracts a set of values out of a target string based on a template string.
template
must be a string containing one or more parameters in any allowed format- Returns an object in
parameter: value
format
const { extract } = require('hokey-cokey');
extract("places/{country}/{city}", "places/france/paris");
extract("places/:country/:city", "places/france/paris");
render(template, values)
Inject values into a template
Render a set of values into a template string.
template
must be a string containing one or more parameters in any allowed formatvalues
can be:
- An object containing string or function keys (keys must correspond to parameters in the template or render will fail)
- A function called for each parameter (receives the parameter name)
- A single string used for all parameters
- Returns the rendered string
const { render } = require("hokey-cokey");
render("blogs-:category-:slug", { category: "cheeses", slug: "stilton" });
render("blogs-:category-:slug", "Arrrrgh");
render("blogs-:category-:slug", (p) => p.toUpperCase());
params(template)
Get parameter names from template string
Parse a template string and return an array of found variables that were found.
template
must be a string containing one or more parameters in any allowed format- Returns an array of string parameter names that were found in the template
const { params } = require("hokey-cokey");
params("{username}@{domain}");
params(":name // ${age}");