Skip to content

Commit 821444a

Browse files
committed
Add support for arrays. Fixes #2, #1
The function can now be called on arrays as well as strings. This is useful for strings where multiple replacements are necessary, since it means the function can be called on its own result.
1 parent 1b3d130 commit 821444a

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

index.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33

44
var isRegExp = require('lodash.isregexp');
55
var escapeRegExp = require('lodash.escaperegexp');
6+
var isString = require('lodash.isstring');
7+
var isArray = require('lodash.isarray');
8+
var flatten = require('lodash.flatten');
69

710
/**
811
* Given a string, replace every substring that is matched by the `match` regex
@@ -27,9 +30,9 @@ var escapeRegExp = require('lodash.escaperegexp');
2730
* @param {function} fn
2831
* @return {array}
2932
*/
30-
module.exports = function reactStringReplace(str, match, fn) {
33+
function replaceString(str, match, fn) {
3134
if (typeof str !== 'string' || !str) {
32-
throw new TypeError('First argument to react-string-replace must be a non-empty string');
35+
throw new TypeError('First argument to react-string-replace#replaceString must be a string');
3336
}
3437

3538
var re = match;
@@ -46,4 +49,18 @@ module.exports = function reactStringReplace(str, match, fn) {
4649
}
4750

4851
return result;
52+
}
53+
54+
module.exports = function reactStringReplace(str, match, fn) {
55+
if (isString(str)) {
56+
str = [str];
57+
}
58+
59+
if (!isArray(str) || !str[0]) {
60+
throw new TypeError('First argument to react-string-replace must be an array or non-empty string');
61+
}
62+
63+
return flatten(str.map(function(x) {
64+
return isString(x) ? replaceString(x, match, fn) : x;
65+
}));
4966
};

0 commit comments

Comments
 (0)