UNPKG

@scalar/oas-utils

Version:

Open API spec and Yaml handling utilities

19 lines (17 loc) 755 B
/** * This function takes a string and replace {variables} with given values. */ function replaceVariables(value, variablesOrCallback) { // Replace all variables (example: {{ baseurl }} with an HTML tag) const doubleCurlyBrackets = /{{\s*([\w.-]+)\s*}}/g; const singleCurlyBrackets = /{\s*([\w.-]+)\s*}/g; const callback = (_, match) => { if (typeof variablesOrCallback === 'function') { return variablesOrCallback(match); } return variablesOrCallback[match]?.toString() || `{${match}}`; }; // Loop through all matches and replace the match with the variable value return value.replace(doubleCurlyBrackets, callback).replace(singleCurlyBrackets, callback); } export { replaceVariables };