Search code examples
javascriptarraysstringnumbersfloating

How can I extract each integer or float (positive or negative) from a string in js


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));


Solution

  • 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)