Last active
May 6, 2022 12:47
-
-
Save worldoptimizer/178b4617b106d5c0dd9dbcfba051c41c to your computer and use it in GitHub Desktop.
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
/** | |
* 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