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#485 from david-luna/master
feat(string): format string like Java
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 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 |
---|---|---|
@@ -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 | ||
``` |