Created
October 8, 2021 18:12
-
-
Save alexsc6955/0d0d79d5ede93b8f7055ce6eb74005be to your computer and use it in GitHub Desktop.
Async function to replace words between brackets
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
/** | |
* 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: "[email protected]" | |
* } | |
* ) | |
* .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: "[email protected]" | |
* } | |
* ); | |
* 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