@stackend/api
Version:
JS bindings to api.stackend.com
55 lines • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.templateReplaceUrl = exports.templateReplace = exports.TEMPLATE_END = exports.TEMPLATE_START = void 0;
exports.TEMPLATE_START = '{{';
exports.TEMPLATE_END = '}}';
/**
* Replace occurrences of {{XXX}} with the values of XXX from the values.
* For example templateReplace("Hello {{name}}!", { name: 'Jane' }) would return "Hello Jane!"
* @param template
* @param values
* @param valueEncoder
* @returns {string}
*/
function templateReplace(template, values, valueEncoder) {
if (!template) {
return template;
}
var sb = '';
// Special cases
// "Hello {currentUser.name}, how are you?"
// "Hello { code"
var s = 0;
do {
var i = template.indexOf(exports.TEMPLATE_START, s);
if (i === -1) {
// No more stuff, add the remainder
sb += template.substring(s);
break;
}
// Add everything before {
sb += template.substring(s, i);
var e = template.indexOf(exports.TEMPLATE_END, i + exports.TEMPLATE_START.length);
if (e === -1) {
// No more stuff, add the remainder
sb += template.substring(i);
break;
}
var n = template.substring(i + exports.TEMPLATE_START.length, e);
var v = values[n];
if (v) {
sb += valueEncoder ? valueEncoder(v) : v;
}
s = e + exports.TEMPLATE_END.length;
} while (s < template.length);
return sb;
}
exports.templateReplace = templateReplace;
function templateReplaceUrl(url, replacements) {
if (!url) {
return url;
}
return encodeURI(templateReplace(url, replacements));
}
exports.templateReplaceUrl = templateReplaceUrl;
//# sourceMappingURL=templateReplace.js.map