I am using the async/await function the following way
async function(){
let output = await string.replace(regex, async (match)=>{
let data = await someF
This replaceAsync
function iterates through all occurrences of a substring in a string by a regex and enable you to use an asynchronous exampleReplaceFunc
function to replace them one by one (e.g. based on the match group as parameter).
const replaceAsync = async (str, regex, getNewSubstr) => {
while (str.match(regex)) {
const result = str.match(regex);
const { index } = result;
const [match, group1] = result;
const newSubstr = await getNewSubstr(match, group1);
str = `${str.substr(0, index)}${newSubstr}${str.substr(
index + match.length
)}`;
}
return str;
};
const exampleReplaceFunc = async (match, group) => {
return new Promise(resolve => {
setTimeout(() => {
console.log(`'${match}' has been changed to 'new${group}'`);
resolve(`new${group}`);
}, 1500);
});
};
const app = async () => {
const str = "aaaaold1 aaold2aa aold3aa old4 aold5aa";
console.log('original string:', str)
const newStr = await replaceAsync(str, /old([\d])/, exampleReplaceFunc);
console.log('new string:', newStr);
};
app();