1

I'm trying to run a function taking as a parameter the matching criteria of a replace call, but I'm struggling with it. In the scenario of:

x="foo OFFSET_5 bar";
regex=/OFFSET_(-?[0-9]*)\b/g;
function timesThree(n){  return n*3 }

If I do a simple x.replace(regex, '$1') the output is, as expected, foo 5 bar. However, I want to pass that 5 to timesThree, I'm unable to, getting always NaNinstead of 15.

I tried x.replace(regex, timesThree($1)), but to no avail.

Where is my code failing?

Thanks in advance

3
  • timesThree(parseInt(x.split("_")[1])) Commented Oct 16, 2019 at 9:41
  • @mplungjan - OP seems to want to use this as part of a replace. Commented Oct 16, 2019 at 9:43
  • Hence I did not post an answer Commented Oct 16, 2019 at 9:48

1 Answer 1

1

You'd do it with a wrapper function around the call:

x.replace(regex, (m, c0) => timesThree(c0));

Live Example:

const x = "foo OFFSET_5 bar";
const regex = /OFFSET_(-?[0-9]*)\b/g;
function timesThree(n){  return n*3 }
console.log(x.replace(regex, (m, c0) => timesThree(c0)));

or in ES5:

x.replace(regex, function(m, c0){ return timesThree(c0); });

Live Example:

var x = "foo OFFSET_5 bar";
var regex = /OFFSET_(-?[0-9]*)\b/g;
function timesThree(n){  return n*3 }
console.log(x.replace(regex, function(m, c0){ return timesThree(c0); }));

That works because the function is called with the overall match as the first argument (m, which we don't use), and then each capture group's captured text as a subsequent argument (c0 in this case). So we pass the first capture group's text into timesThree, which converts the string to number implicitly via *. The resulting number is implicitly converted back to string and inserted.

Sign up to request clarification or add additional context in comments.

1 Comment

@ Anonymous User - Thanks for catching the const thing in the ES5!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.