Last active
January 31, 2023 08:04
-
-
Save fedeghe/7562904 to your computer and use it in GitHub Desktop.
A useful function to give values to a template full of placeholders
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
/** | |
* [ description] | |
* @param {string} tpl the template | |
* @param {literal|function} obj a literal for substitution or a function that will | |
* return the substitution given as parameter a string | |
* @param {string} start optional- the opening placeholder delimitator (%) | |
* @param {string} end optional- the closing placeholder delimitator (%) | |
* @param {string} fb optional- a fallback value in case an element is not found | |
* @return {string} the resulting string with replaced values | |
*/ | |
function replaceall(tpl, obj, start, end, fb) { | |
start || (start = '%'); | |
end || (end = '%'); | |
var reg = new RegExp(start + '([A-z0-9-_]*)' + end, 'g'), | |
straight = true, | |
str, tmp; | |
while (straight) { | |
if (!(tpl.match(reg))) { | |
return tpl; | |
} | |
tpl = tpl.replace(reg, function (str, $1) { | |
switch (true) { | |
// | |
case typeof obj === 'function' : | |
// avoid silly infiloops | |
tmp = obj($1); | |
return (tmp !== start + $1 + end) ? obj($1) : $1; | |
break; | |
// the label matches a obj literal element | |
// use it | |
case $1 in obj : return obj[$1]; break; | |
// not a function and not found in literal | |
// use fallback if passed or get back the placeholder | |
// switching off before returning | |
default: | |
straight = false; | |
return typeof fb !== 'undefined' ? fb : start + $1 + end; | |
break; | |
} | |
}); | |
} | |
return tpl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
another simplified version