Last active
June 3, 2023 23:33
-
-
Save intrnl/6030836461d82e5d093744f28553628a to your computer and use it in GitHub Desktop.
Asynchronous string replace
This file contains 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
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