Last active
March 25, 2021 15:39
-
-
Save GluTbl/85e58fbd2d0adc31d73c719e0104321b to your computer and use it in GitHub Desktop.
[Text formating at Js]
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
//Source https://stackoverflow.com/questions/7975005/format-a-javascript-string-using-placeholders-and-an-object-of-substitutions | |
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.'; | |
const replacements = { | |
name: 'Mike', | |
age: '', | |
}; | |
function formate(old_string,replacement_dict) { | |
return old_string.replace( | |
/{(\w+)}/g, | |
(placeholderWithDelimiters, placeholderWithoutDelimiters) => | |
replacement_dict.hasOwnProperty(placeholderWithoutDelimiters) ? | |
replacement_dict[placeholderWithoutDelimiters] : placeholderWithDelimiters | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment