Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Last active June 3, 2026 12:05
Show Gist options
  • Select an option

  • Save jonathanconway/2400b55606db976524fd7560859c1856 to your computer and use it in GitHub Desktop.

Select an option

Save jonathanconway/2400b55606db976524fd7560859c1856 to your computer and use it in GitHub Desktop.
Flexible template parser
/**
* Parses a templated expression for fields.
* Token opening and closing delimiters can be customised.
*/
function parseTemplate({
input,
tokenDelimiters: {
open,
close,
} = {
open: "{",
close: "}",
}
}: {
input: string,
tokenDelimiters: {
open: string;
close: string;
}
}) {
const fieldPattern = new RegExp(
[
open,
"(.*?)",
close,
].join(""),
"g"
);
const inputMatches = Array.from(input.matchAll(fieldPattern));
return inputMatches;
}
const testParams = {
input: `Good {timeOfDay}, {personName}.`,
tokenDelimiters: {
open: "{",
close: "}"
}
};
const result = parseTemplate(testParams);
console.log(result);
// Output:
// [
// [
// '<timeOfDay>',
// 'timeOfDay',
// index: 5,
// input: 'Good <timeOfDay>, <personName>.',
// groups: undefined
// ],
// [
// '<personName>',
// 'personName',
// index: 18,
// input: 'Good <timeOfDay>, <personName>.',
// groups: undefined
// ]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment