Last active
June 3, 2026 12:05
-
-
Save jonathanconway/2400b55606db976524fd7560859c1856 to your computer and use it in GitHub Desktop.
Flexible template parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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