Skip to content

Instantly share code, notes, and snippets.

@fedeghe
Last active January 31, 2023 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedeghe/7562904 to your computer and use it in GitHub Desktop.
Save fedeghe/7562904 to your computer and use it in GitHub Desktop.
A useful function to give values to a template full of placeholders
/**
* [ 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;
}
@fedeghe
Copy link
Author

fedeghe commented Jan 29, 2023

another simplified version

const replaceAll = (tpl, o, opts = {}) => {
  const delimStart = opts?.start || '%',
        delimEnd = opts?.end || '%',
        fb = opts?.fb,
        reg = new RegExp(
          `${delimStart}(\\\+)?([A-z0-9-_\.]*)${delimEnd}`,
          'gm'
        );
  return tpl.replace(reg, (str, enc, $1) => o[$1] || fb($1) || $1);
}


console.log(replaceAll(
   'kill &who% &howmany% (&cmt%)',
   {who: '\'em', cmt: 'u asked howmany right?'},
   {start:'&', fb: n => `all!`}
))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment