Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active June 3, 2023 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/6030836461d82e5d093744f28553628a to your computer and use it in GitHub Desktop.
Save intrnl/6030836461d82e5d093744f28553628a to your computer and use it in GitHub Desktop.
Asynchronous string replace
function stringReplaceAsync (string, regex, replacer) {
if (!regex.global) {
const match = regex.exec(string)
if (!match) return string
const retVal = replacer(...match, match.index, string)
if (retVal instanceof Promise) {
return retVal.then((ret) => (
string.slice(0, match.index) +
ret +
string.slice(match.index + match[0].length)
))
} else {
return (
string.slice(0, match.index) +
retVal +
string.slice(match.index + match[0].length)
)
}
} else {
const accu = []
let promise = false
let match
let lastIndex = 0
while ((match = regex.exec(string)) !== null) {
accu.push(string.slice(lastIndex, match.index))
const retVal = replacer(...match, match.index, string)
if (retVal instanceof Promise) {
promise = true
}
accu.push(retVal)
lastIndex = regex.lastIndex
}
accu.push(string.slice(lastIndex))
return promise
? Promise.all(accu).then((arr) => arr.join(''))
: accu.join('')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment