0

This javascript code needs to pass the invoke the function convert and use its returned value to replace every match. But it is not sending the cid value to the convert function. Any idea how to? Thanks

const convert = function (cid) {
    console.log('got: ' + cid); // got NAN
    const converted = Math.round(Number(cid) * 16.3871);
    console.log(converted);
    return converted
};
    return myStr.replace(/(\d{3})/g, convert('$1'));
}
1
  • It would be good if you post the complete function code Commented Sep 7, 2017 at 8:07

1 Answer 1

1

Don't invoke the convert function as the second replace parameter. It will be invoked automatically and pass $1 match on its own as 1st convert argument. And the second return is incorrect (out of function).

const convert = function (cid) {
      console.log('got: ' + cid); // got NAN
      const converted = Math.round(Number(cid) * 16.3871);
      console.log(converted);
      return converted;
    };

var someString = 'abc134def';

console.log(someString.replace(/(\d{3})/g, convert));
Sign up to request clarification or add additional context in comments.

Comments

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.