0

I have some code that searches through text for match, then when it finds a match, performs a non-trivial transformation on the matched text, which I then want to replace with the result of this transformation. For example (ignoring Zalgo issues):

var text = "foo bar <sum>(10+33)/pi</sum> baz";
var matches = text.match(/<sum>[\s\S]+?<\/sum>/g);
matches.forEach(element => {
    var result = evaluateSum(element);
    // Now somehow replace element with result
});

I could cobble together a hack with RegExp.exec(), but there must be a neat way of doing this task.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114

2 Answers2

1

You can pass a callback to replace() to calculate an arbitrary replacement.

See the documentation for more details.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Instead of using a forEach(), I would use a reduce() and reduce down the string.

const evaluateSum = () => 100;

var text = "foo bar <sum>(10+33)/pi</sum> baz";
var matches = text.match(/<sum>[\s\S]+?<\/sum>/g);
const replacedText = matches.reduce((result, element) =>
  result.replace(element, evaluateSum(element)), text);
  
console.log(replacedText);

reduce() will loop through each element in an array, do something, return that something, and keep going until it's done that something for each element in the array.

It's a handy way to crunch down anything with an array to a single value.

samanime
  • 25,408
  • 15
  • 90
  • 139