Skip to content

Instantly share code, notes, and snippets.

@ratiw
Last active Jan 22, 2020
Embed
What would you like to do?
JS function to extract variables from template string
function extract_vars(template, openChar, closeChar) {
openChar = openChar || '{';
closeChar = closeChar || '}';
var i = 0;
var data = [];
do {
if (template[i] == '{') {
for (var j=i+1; j<template.length; j++) {
if (template[j] == '}') {
data[data.length] = template.slice(i+1, j);
i = j+1;
break;
}
}
}
} while (++i < template.length);
return data;
}
function parse_vars(vars, delimiter) {
delimiter = delimiter || ':';
return vars.map(function(item) {
var a = item.split(delimiter);
return { name: a[0], default: a[1] };
});
}
var aa = extract_vars("The {adj} {color:brown} fox jumps over the lazy {animal:dog}.");
console.log(aa);
var vars = parse_vars(aa);
console.log(vars);
console.log(vars[0].default ? 'has default' : 'no default');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment