UNPKG

951 BJavaScriptView Raw
1var toString = require('../lang/toString');
2var toArray = require('../lang/toArray');
3
4 /**
5 * Replace string(s) with the replacement(s) in the source.
6 */
7 function replace(str, search, replacements) {
8 str = toString(str);
9 search = toArray(search);
10 replacements = toArray(replacements);
11
12 var searchLength = search.length,
13 replacementsLength = replacements.length;
14
15 if (replacementsLength !== 1 && searchLength !== replacementsLength) {
16 throw new Error('Unequal number of searches and replacements');
17 }
18
19 var i = -1;
20 while (++i < searchLength) {
21 // Use the first replacement for all searches if only one
22 // replacement is provided
23 str = str.replace(
24 search[i],
25 replacements[(replacementsLength === 1) ? 0 : i]);
26 }
27
28 return str;
29 }
30
31 module.exports = replace;
32
33