Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Created August 28, 2021 00:27
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 dSalieri/1ce7f233f00c11991333c2dae653fde3 to your computer and use it in GitHub Desktop.
Save dSalieri/1ce7f233f00c11991333c2dae653fde3 to your computer and use it in GitHub Desktop.
Text replacer, it replaces source string with special keywords on required values
function replaceMatches(template, objReplacer, objData){
if(typeof template !== "string") return null;
if(typeof objReplacer !== "object") return template;
objData = objData || {};
for(let key of Object.keys(objReplacer)){
if(!Object.hasOwnProperty.call(objData, key)) continue;
template = template.replace(new RegExp(objReplacer[key],"g"), objData[key])
}
return template;
}
/// Example of usage
let data = {
name: "dSalieri",
power: "valuable"
};
let replacer = {
name: "%userName%",
power: "%power%"
};
console.log(replaceMatches("My name is %userName%, I'll show you a %power% thing. There was %userName% with you, see you", replacer, data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment