Skip to content

Instantly share code, notes, and snippets.

@danguilherme
Created July 5, 2021 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danguilherme/79ccec6c37e6f0f8beca5e6883a290d8 to your computer and use it in GitHub Desktop.
Save danguilherme/79ccec6c37e6f0f8beca5e6883a290d8 to your computer and use it in GitHub Desktop.
Function to replace variables in a string
export function replaceVars(
content: string,
variables: { [key: string]: string }
) {
const varRegex = /\$([a-z0-9_]*)/gi;
let match: RegExpExecArray;
while ((match = varRegex.exec(content)!)) {
let [wholeVar, varName] = match;
const varValue = variables[varName];
if (varValue === undefined || varValue === null)
throw new Error(`Replacement variable not found: ${wholeVar}`);
content = content.replace(
new RegExp(escapeSpecialRegexChars(wholeVar), "g"),
varValue
);
}
return content;
}
function escapeSpecialRegexChars(str: string) {
return str.replace(/([$\\_])/g, "\\$1");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment