Skip to content

Commit

Permalink
Merge pull request phuocng#486 from 1milligram/format-str
Browse files Browse the repository at this point in the history
Format a string
  • Loading branch information
phuocng authored Nov 11, 2021
2 parents 114bc36 + 023808b commit b55f9fd
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions snippets/string/format-a-string.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
---
title: Format a String (Java style)
title: Format a string
category: String
---

**JavaScript version**

```js
const format = (str, ...vals) => vals.reduce((s,v,i) => s.replace(new RegExp('\\{' + i + '\\}', 'g'), v), str)
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);
```ts
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
format(template, 'John', 30));
// 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
format(template, 'Jane', 20);
// My name is Jane and I am 20 years old
```

0 comments on commit b55f9fd

Please sign in to comment.