Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit d0fa968

Browse files
committed
Clean up string format solution with something a little more efficient. From #26.
1 parent 69bad3a commit d0fa968

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

string-format/README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
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.
24

35
## Example
46

57
```
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}'
810
```
911

1012
By [Riga](https://github.com/riga).

string-format/string-format.js

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
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);
63

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+
});
127
};

0 commit comments

Comments
 (0)