Skip to content

Instantly share code, notes, and snippets.

@worldoptimizer
Last active May 6, 2022 12:47
Show Gist options
  • Save worldoptimizer/178b4617b106d5c0dd9dbcfba051c41c to your computer and use it in GitHub Desktop.
Save worldoptimizer/178b4617b106d5c0dd9dbcfba051c41c to your computer and use it in GitHub Desktop.
/**
* Resolve variables in string using a variable lookup
*
* @param {string} str The string to resolve variables in.
* @param {object} variables The variables to resolve.
* @returns {string} The resolved string.
*/
function resolveVariablesInString(str, variables) {
if (typeof str === 'string') {
var matches = str.match(/\${.*?}|%{.*?}|✨{.*?}/g);
if (matches) {
matches.forEach(function(match) {
var variableKey = match.replace(/\$\{|\%\{|\✨\{|\}|\(\)/g, '');
var variableValue = resolveObjectByKey(variables, variableKey);
str = str.replace(match, variableValue);
});
}
}
return str;
}
// Alternate version with indexOf
function resolveVariablesInString(str, variables) {
if (typeof str === 'string') {
do {
var startString = '${';
var startIndex = str.indexOf(startString);
if (startIndex == -1) {
startString = '✨{';
startIndex = str.indexOf(startString);
}
var endIndex = str.indexOf('}', startIndex);
if (startIndex > -1 && endIndex > -1) {
var variableKey = str.substring(startIndex + 2, endIndex);
var variableValue = resolveObjectByKey(variables, variableKey);
str = str.replace(startString + variableKey + '}', variableValue);
}
} while (startIndex > -1);
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment