mout
Version:
Modular Utilities
30 lines (23 loc) • 826 B
text/typescript
import toString from '../lang/toString';
import toArray from '../lang/toArray';
/**
* Replace string(s) with the replacement(s) in the source.
*/
function replace(str, search, replacements) {
str = toString(str);
search = toArray(search);
replacements = toArray(replacements);
const searchLength = search.length;
const replacementsLength = replacements.length;
if (replacementsLength !== 1 && searchLength !== replacementsLength) {
throw new Error('Unequal number of searches and replacements');
}
let i = -1;
while (++i < searchLength) {
// Use the first replacement for all searches if only one
// replacement is provided
str = str.replace(search[i], replacements[replacementsLength === 1 ? 0 : i]);
}
return str;
}
export default replace;