Last active
February 8, 2024 08:26
-
-
Save jonschlinkert/46075d13d9da9f1c549dd995b7670ef4 to your computer and use it in GitHub Desktop.
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 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