Created
August 28, 2021 00:27
-
-
Save dSalieri/1ce7f233f00c11991333c2dae653fde3 to your computer and use it in GitHub Desktop.
Text replacer, it replaces source string with special keywords on required values
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
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