[removed] Async/await in .replace

前端 未结 4 1311
情话喂你
情话喂你 2021-02-05 06:00

I am using the async/await function the following way

async function(){
  let output = await string.replace(regex, async (match)=>{
    let data = await someF         


        
4条回答
  •  抹茶落季
    2021-02-05 06:24

    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();

提交回复
热议问题