Skip to content

Instantly share code, notes, and snippets.

@SeanCassiere
Last active May 30, 2023 09:08
Show Gist options
  • Save SeanCassiere/89ef8dbd84a958f486ab99a1cd30fc63 to your computer and use it in GitHub Desktop.
Save SeanCassiere/89ef8dbd84a958f486ab99a1cd30fc63 to your computer and use it in GitHub Desktop.
Parsing and replacing marked tags with values from an object
const dataObject = {
firstName: "John",
lastName: "Doe",
// age // the parse fn will attempt to access this variable which does not exist
fullName: "John Doe",
};
type DataObjectInput = Record<string, string | number | null>;
function parseStringWithTemplateLiteralVariables(rawString = "", variables: DataObjectInput = {}) {
return rawString
.replace(/\$\{(.*?)\}/g, (_, p1) => {
if (p1 in variables) {
return `${variables[p1]}`;
}
return "${" + p1 + "}"; // controls what is returned when the dataObject doesn't contain the key (i.e. p1)
})
.trim();
}
function parseStringWithPercentageTagVariables(rawString = "", variables: DataObjectInput = {}) {
return rawString
.replace(/%%(.*?)%%/g, (_, p1) => {
if (p1 in variables) {
return `${variables[p1]}`;
}
return `%%${p1}%%`; // controls what is returned when the dataObject doesn't contain the key (i.e. p1)
})
.trim();
}
const templateLiteralString = "${firstName} ${lastName} ${age} is a person.";
console.log("------------------------\ntemplate literals\n------------------------");
console.log("raw: ", templateLiteralString);
console.log("parsed: ", parseStringWithTemplateLiteralVariables(templateLiteralString, dataObject)); // output is "John Doe ${age} is a person."
const doublePercentageString = "%%firstName%% %%lastName%% %%age%% is a person.";
console.log("\n------------------------\nDouble %% wrappers\n------------------------");
console.log("raw: ", doublePercentageString);
console.log("parsed: ", parseStringWithPercentageTagVariables(doublePercentageString, dataObject)); // output is "John Doe %%age%% is a person."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment