Skip to content

Instantly share code, notes, and snippets.

@simonkberg
Created May 30, 2016 13:55
Show Gist options
  • Select an option

  • Save simonkberg/0814ca69753597a7f4e3d4b1ca62eafb to your computer and use it in GitHub Desktop.

Select an option

Save simonkberg/0814ca69753597a7f4e3d4b1ca62eafb to your computer and use it in GitHub Desktop.
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