Created
May 30, 2016 13:55
-
-
Save simonkberg/0814ca69753597a7f4e3d4b1ca62eafb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import flatten from './flatten' | |
| export const replaceString = (input, pattern, replace) => { | |
| const index = input.indexOf(pattern) | |
| const isFunction = typeof replace === 'function' | |
| if (index >= 0) { | |
| const output = [] | |
| const lastIndex = index + pattern.length | |
| if (index > 0) { | |
| output.push(input.substring(0, index)) | |
| } | |
| const result = input.substring(index, lastIndex) | |
| output.push( | |
| isFunction | |
| ? replace(result, index, input) | |
| : replace | |
| ) | |
| if (lastIndex < input.length) { | |
| output.push(input.substring(lastIndex)) | |
| } | |
| return output | |
| } | |
| return [input] | |
| } | |
| export const replaceRegExp = (input, regexp, replace) => { | |
| const output = [] | |
| const storedLastIndex = regexp.lastIndex | |
| const isFunction = typeof replace === 'function' | |
| regexp.lastIndex = 0 | |
| let result = regexp.exec(input) | |
| let lastIndex = 0 | |
| while (result) { | |
| const index = result.index | |
| if (index !== lastIndex) { | |
| output.push(input.substring(lastIndex, index)) | |
| } | |
| const match = result[0] | |
| lastIndex = index + match.length | |
| output.push( | |
| isFunction | |
| ? replace(...result.concat(index, result.input)) | |
| : replace | |
| ) | |
| result = regexp.exec(input) | |
| } | |
| if (lastIndex < input.length) { | |
| output.push(input.substring(lastIndex)) | |
| } | |
| regexp.lastIndex = storedLastIndex | |
| return output | |
| } | |
| export default function replace (input, pattern, replace) { | |
| const fn = pattern instanceof RegExp ? replaceRegExp : replaceString | |
| if (typeof input === 'string') { | |
| return fn(input, pattern, replace) | |
| } | |
| if (Array.isArray(input)) { | |
| return flatten(input.map(value => { | |
| return typeof value === 'string' | |
| ? fn(value, pattern, replace) | |
| : value | |
| })) | |
| } | |
| throw new TypeError('First argument must be an array or a string') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment