[d24f17c] | 1 | import { replace } from 'ramda';
|
---|
| 2 |
|
---|
| 3 | import isRegExp from '../../isRegExp';
|
---|
| 4 | import escapeRegExp from '../../escapeRegExp';
|
---|
| 5 |
|
---|
| 6 | const checkArguments = (searchValue, replaceValue, str) => {
|
---|
| 7 | if (str == null || searchValue == null || replaceValue == null) {
|
---|
| 8 | throw TypeError('Input values must not be `null` or `undefined`');
|
---|
| 9 | }
|
---|
| 10 | };
|
---|
| 11 |
|
---|
| 12 | const checkValue = (value, valueName) => {
|
---|
| 13 | if (typeof value !== 'string') {
|
---|
| 14 | if (!(value instanceof String)) {
|
---|
| 15 | throw TypeError(`\`${valueName}\` must be a string`);
|
---|
| 16 | }
|
---|
| 17 | }
|
---|
| 18 | };
|
---|
| 19 |
|
---|
| 20 | const checkSearchValue = (searchValue) => {
|
---|
| 21 | if (
|
---|
| 22 | typeof searchValue !== 'string' &&
|
---|
| 23 | !(searchValue instanceof String) &&
|
---|
| 24 | !(searchValue instanceof RegExp)
|
---|
| 25 | ) {
|
---|
| 26 | throw TypeError('`searchValue` must be a string or an regexp');
|
---|
| 27 | }
|
---|
| 28 | };
|
---|
| 29 |
|
---|
| 30 | const replaceAll = (searchValue, replaceValue, str) => {
|
---|
| 31 | checkArguments(searchValue, replaceValue, str);
|
---|
| 32 | checkValue(str, 'str');
|
---|
| 33 | checkValue(replaceValue, 'replaceValue');
|
---|
| 34 | checkSearchValue(searchValue);
|
---|
| 35 |
|
---|
| 36 | const regexp = new RegExp(
|
---|
| 37 | isRegExp(searchValue) ? searchValue : escapeRegExp(searchValue),
|
---|
| 38 | 'g'
|
---|
| 39 | );
|
---|
| 40 |
|
---|
| 41 | return replace(regexp, replaceValue, str);
|
---|
| 42 | };
|
---|
| 43 |
|
---|
| 44 | export default replaceAll;
|
---|