Skip to content

Instantly share code, notes, and snippets.

@jonschlinkert
Last active February 8, 2024 08:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonschlinkert/46075d13d9da9f1c549dd995b7670ef4 to your computer and use it in GitHub Desktop.
Save jonschlinkert/46075d13d9da9f1c549dd995b7670ef4 to your computer and use it in GitHub Desktop.
const replace = async (input, regex, replacer) => {
// we need to remove the 'g' flag, if defined, so that all replacements can be made
let flags = (regex.flags || '').replace('g', '');
let re = new RegExp(regex.source || regex, flags);
let index = 0;
let match;
while ((match = re.exec(input.slice(index)))) {
let value = await replacer(...match);
index += match.index;
input = input.slice(0, index) + value + input.slice(index + match[0].length);
index += match[0].length;
// if 'g' was not defined on flags, break
if (flags === regex.flags) {
break;
}
}
return input;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment