replace.js 951 B

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