Created
February 27, 2023 09:02
-
-
Save kingRayhan/b156078b1363f0f8b008ebfc920c5b63 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Replaces the string with the object key value | |
* @param obj - object to be replaced | |
* @param data - string to be replaced | |
* @param variableIdentifiers | |
* @returns string | |
* | |
* @example | |
* replacer({ name: "Rayhan", age: 26 }, "my name is #name# and my age is #age#", ["#_#", "{{_}}"]) | |
* // returns "my name is Rayhan and my age is 26" | |
* | |
* replacer({ name: "Rayhan", age: 26 }, "my name is #name# and my age is #age#", ["#_#", "{{_}}", "%_%"]) | |
* // returns "my name is Rayhan and my age is 26" | |
* | |
*/ | |
function variableInjector(variables: { [key: string]: any }, data: string, variableIdentifiers: string[] = ["#_#", "{{_}}", "%_%"]) { | |
let newString = data; | |
const keys = Object.keys(variables); | |
keys.forEach((key) => { | |
variableIdentifiers.forEach((identifier) => { | |
const [start, end] = identifier.split("_"); | |
let regEx = new RegExp(`${start}\\s*${key}\\s*${end}`, "g"); | |
newString = newString.replace(regEx, variables[key]); | |
}); | |
}); | |
return newString; | |
} | |
export default variableInjector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment