Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created April 24, 2018 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/370f9a476648b0a8ce6130e1cb0c2893 to your computer and use it in GitHub Desktop.
Save ycmjason/370f9a476648b0a8ce6130e1cb0c2893 to your computer and use it in GitHub Desktop.
Async version of `string.prototype.replace`
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