-1

I’m trying to use a variable in a RegEx and I’m having problems. This is my function:

const truncateNum = (num, place = 2) => {
  const matcher = `/^-?\d+(?:\.\d{0,${place}})?/`;
  const re = new RegExp(matcher);
  return num.toString().match(re)[0];
};

When running this I get the following error:

Uncaught TypeError: Cannot read property '0' of null

What am I doing wrong here?

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101
  • The problem lies in meta character escaping. Place this `^\\-?\\d+(?:\\.\\d{0,${place}})?` in your template literal to solve the problem. – Shuvojit Saha Jul 12 '20 at 17:51

1 Answers1

3

There are a few issues with your code.

The first is that when you define a regex as a string, it doesn't require // marks, and also backslashes need to be double escaped \\d+.

The second is that num.toString().match(re) will return null if the regular expression doesn't match, thus you are getting an exception from trying to do an array lookup on null[0].

let truncateNum = (num, place = 2) => {
  const  matcher = `^-?\\d+(?:\\.\\d{0,${place}})?`; console.log(matcher);
  const  re      = new RegExp(matcher);
  const  match   = num.toString().match(re);
  const  result  = match && match[0] || '0'
  return result;
};
James McGuigan
  • 7,542
  • 4
  • 26
  • 29