1

This is my code. It still returns null and I do not know why!

var tName = "18.56x^2   -   5.45x  -3.78";
abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, "");
console.log(abc);

$re = "/-?\\d+(?:\\.\\d+)?/m";
$str = abc.toString();
console.log($str.match($re));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
7Wdev
  • 47
  • 7

3 Answers3

3

Your regex is fine, you just set it up as a string instead of a regex literal.

When you are building RegExp constants, you want to either use the RegExp() constructor (for building from strings) or simply a regex literal. You are currently building a normal string that looks like a regex, but isn't.

Try edit this line to the following:

$re = /-?\d+(?:\.\d+)?/m;

Edit:

To access the string itself, you just need to use index 0.

var mat = $str.match($re);
console.log(mat[0])
Keldan Chapman
  • 665
  • 5
  • 21
1

use regexp (not String) as param of String.prototype.match() like this:

var tName = "18.56x^2   -   5.45x  -3.78";
abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, "");

$re = /-?\d+(?:\.\d+)?/m;
$str = abc.toString();
console.log($str.match($re));
Joy
  • 41
  • 3
1

You need to

  • not quote the regex AND
  • not escape the \d AND
  • add the global flag

Have a try with this

const $re = /-?\d+(?:\.\d+)?/mg,
      tName = "18.56x^2   -   5.45x  -3.78",
      abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, ""),
      nums = [...abc.matchAll($re)].map(m => m[0]);
console.log(abc)
console.log(nums)
mplungjan
  • 169,008
  • 28
  • 173
  • 236