From 5618e1924615d9e4415ef1dc4ebac80d7fa77dec Mon Sep 17 00:00:00 2001 From: David Luna Date: Tue, 9 Nov 2021 23:24:25 +0100 Subject: [PATCH] feat(string): format string like Java --- snippets/string/format-a-string.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 snippets/string/format-a-string.md diff --git a/snippets/string/format-a-string.md b/snippets/string/format-a-string.md new file mode 100644 index 00000000..08966b3d --- /dev/null +++ b/snippets/string/format-a-string.md @@ -0,0 +1,30 @@ +--- +title: Format a String (Java style) +category: String +--- + +**JavaScript version** + +```js +const format = (str, ...vals) => vals.reduce((s,v,i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str) +``` + +**TypeScript version** + +```js +const format = (str: string, ...vals: unknown[]): string => vals.reduce((s,v,i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str); +``` + +**Examples** + +```js +const template = 'My name is {0} and I am {1} years old'; +const name1 = 'John', age1 = 30; +const name2 = 'Jane', age2 = 20; + +console.log(format(template, name1, age1)); +// output: My name is John and I am 30 years old + +console.log(format(template, name2, age2)); +// output: My name is Jane and I am 20 years old +```