简体   繁体   中英

Return a value to String.replace from within a callback function

I want to return a value to String.replace from within a callback function. Typing this and posting the code makes me realize how dumb that is.

But, I was hoping there is a way I can achieve the same concept with code that actually works. I feel like it's right in front of me I just can't grasp it.

content.replace(/{{(.*?)}}/g, function (a, b) { 

  recurse(b, function(content2) {
    return content2;
  });

});

Not sure if I got your meaning, but if you intend to return something from the inner function to the outer one, you should be after something like this:

content.replace(/{{(.*?)}}/g, function (a, b) { 

  return recurse(b, function(content2) {
    return content2;
  });

});

If you'r looking for expressions in replacements:

function replacer(matchedSubstring, p1, p2, offset, totalString) {
  return p2 + ' ' + p1.toUpperCase();
}

newString = oldString.replace(/(\w+)\s(\w+)/, replacer);

Please mind that the number of groups in the RegExp and the number of parameters in the replacer's argument list (here: p1, p2) have to match.

See String.replace() at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

You can implement some (probably awful) "locking" concept. I use the term "locking" loosely here. Regardless, it'll force your code into being synchronous.

content.replace(/{{(.*?)}}/g, function (a, b) { 

  var myFakeLock = false;
  var outputToReplace = null;

  var otherCallback = function(someInput) {
      ... // do some stuff here
      outputToReplace = someCalculationResult;
      myFakeLock = true; // last line!
  };

  // Call asynchronous function
  someFunctionWithCallback(otherCallback);

  // Busy-wait until our callback completes
  while (!myFakeLock) { }

  return outputToReplace;
});

I didn't take any care to form a proper closure or anything, so some modification may be needed.

In this solution, the String.replace callback will not return until all of the asynchronous calculation is complete. Be careful how you're using this. You don't want to lock the UI thread this way; call it from some other thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM