Created
April 24, 2018 21:47
-
-
Save ycmjason/370f9a476648b0a8ce6130e1cb0c2893 to your computer and use it in GitHub Desktop.
Async version of `string.prototype.replace`
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
const asyncStringReplace = async (str, regex, aReplacer) => { | |
regex = new RegExp(regex, regex.flags + regex.flags.includes('g')? '': 'g'); | |
const replacedParts = []; | |
let match; | |
let i = 0; | |
while ((match = regex.exec(str)) !== null) { | |
// put non matching string | |
replacedParts.push(str.slice(i, match.index)); | |
// call the async replacer function with the matched array spreaded | |
replacedParts.push(aReplacer(...match)); | |
i = regex.lastIndex; | |
} | |
// put the rest of str | |
replacedParts.push(str.slice(i)); | |
// wait for aReplacer calls to finish and join them back into string | |
return (await Promise.all(replacedParts)).join(''); | |
}; | |
exports default asyncStringReplace; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment