This repository was archived by the owner on Dec 12, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +10
-13
lines changed Expand file tree Collapse file tree 2 files changed +10
-13
lines changed Original file line number Diff line number Diff line change 1
- # String format
1
+ # String Format
2
+
3
+ Create a string formatting function that accepts an input string and a number of arguments to replace positions in the input string.
2
4
3
5
## Example
4
6
5
7
```
6
- format ('Hello {0} {1}', 'Mr.', 'X') // => 'Hello Mr. X'
7
- format ('{1}_{0}', '{1}', '{0}') // => '{0}_{1}'
8
+ f ('Hello {0} {1}', 'Mr.', 'X') // => 'Hello Mr. X'
9
+ f ('{1}_{0}', '{1}', '{0}') // => '{0}_{1}'
8
10
```
9
11
10
12
By [ Riga] ( https://github.com/riga ) .
Original file line number Diff line number Diff line change 1
- /*
2
- * A simple string formatting function
3
- * e.g.: format('Hello {0} {1}', 'Mr.', 'X') => 'Hello Mr. X'
4
- * format('{1}_{0}', '{1}', '{0}') => '{0}_{1}'
5
- */
1
+ var stringFormat = function ( string /* , args */ ) {
2
+ var args = Array . prototype . slice . call ( arguments , 1 ) ;
6
3
7
- var format = function ( s ) {
8
- var i = arguments . length ;
9
- while ( i -- )
10
- s = s . replace ( new RegExp ( '\\{' + ( i - 1 ) + '\\}' , 'gm' ) , String ( arguments [ i ] ) ) ;
11
- return s ;
4
+ return string . replace ( / \{ ( \d + ) \} / g, function ( _ , arg ) {
5
+ return arg in args ? args [ arg ] : _ ;
6
+ } ) ;
12
7
} ;
You can’t perform that action at this time.
0 commit comments