Skip to content

Commit

Permalink
Merge pull request phuocng#485 from david-luna/master
Browse files Browse the repository at this point in the history
feat(string): format string like Java
  • Loading branch information
phuocng authored Nov 11, 2021
2 parents 74b3c14 + 5618e19 commit 114bc36
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions snippets/string/format-a-string.md
Original file line number Diff line number Diff line change
@@ -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
```

0 comments on commit 114bc36

Please sign in to comment.