Last active
January 22, 2020 17:56
-
-
Save ratiw/121872a4ad2ff1dd4587 to your computer and use it in GitHub Desktop.
JS function to extract variables from template string
This file contains 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
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