forked from phuocng/1loc
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request phuocng#486 from 1milligram/format-str
Format a string
- Loading branch information
Showing
1 changed file
with
8 additions
and
10 deletions.
There are no files selected for viewing
This file contains 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
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 | ||
``` |