Skip to content

Instantly share code, notes, and snippets.

@alexsc6955
Created October 8, 2021 18:12
Show Gist options
  • Save alexsc6955/0d0d79d5ede93b8f7055ce6eb74005be to your computer and use it in GitHub Desktop.
Save alexsc6955/0d0d79d5ede93b8f7055ce6eb74005be to your computer and use it in GitHub Desktop.
Async function to replace words between brackets
/**
* Async function to replace words between brackets
*
* E.g.
* replaceBrackets(
* "Hey, {{ name }}. We just sent your authentication code to {{ email||phoneNumber }}",
* {
* name: "Jhon Doe",
* email: "doe@example.com"
* }
* )
* .then(message => {
* console.log(message);
* })
* .catch(error => {
* console.log(error)
* });
*
* You can also use trycatch inside an async function/methos
* async myMethod() {
* try {
* const message = await replaceBrackets(
* "Hey, {{ name }}. We just sent your authentication code to {{ email||phoneNumber }}",
* {
* name: "Jhon Doe",
* email: "doe@example.com"
* }
* );
* console.log(message);
* } catch (error) {
* console.log(error);
* }
* }
*
* @param {String} string The string containing words between brackets
* @param {Object} data Replacement data
* @returns Promise
*/
const replaceBrackets = (string, data) => {
return new Promise((resolve, reject) => {
if (! string) reject("String required");
if (! data) reject("Data required");
const final = string.replace(/\{\{(.+?)\}\}/g, (_, g) => {
let _variable;
let _strArr = g.trim().split("||");
if (_strArr.length > 1) {
_variable = data[_strArr[0].trim()]
? data[_strArr[0].trim()]
: data[_strArr[1].trim()];
} else {
_variable = data[_strArr[0].trim()];
}
return _variable ? _variable : null;
});
resolve(final);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment