parseFloat on regex parameter returning NaN

Viewed 152

I am trying to manipulate some float values inside of a string by a certain amount. To do so I have the following:

var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-190.2,-161.8,-95.1,-230.9,0,-230.9C95.1,-230.9,190.2,-161.8,219.6,-71.4Z" />';
var regex = /[+-]?([0-9]*[.])?[0-9]+/g;
console.log(string.replace(regex, parseFloat("$&") + 300));

How come it is replacing the parseFloat("$&") with NaN? What's the proper way to do this?

2 Answers

Your code is equivalent to writing

var temp = parseFloat("$&") + 300;
document.body.innerText = string.replace(regex, temp);

because function arguments are evaluated before calling the function. "$&" only has special meaning if it's literally in the replacement string that replace() gets, it doesn't have any special meaning to parseFloat(), and it's not possible for replace() to reach into the parseFloat() call and modify the parameter.

If you want to call a function to determine the replacement, you need to pass a function reference to the replace() function, not an expression containing the function call.

var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-190.2,-161.8,-95.1,-230.9,0,-230.9C95.1,-230.9,190.2,-161.8,219.6,-71.4Z" />';
var regex = /[+-]?([0-9]*[.])?[0-9]+/g;
var newString = string.replace(regex, match => parseFloat(match) + 300);
console.log(newString)

See the parseFloat definition

A floating point number parsed from the given value. If the value cannot be converted to a number, NaN is returned.

So clearly you have a string there which can't be converted to a Number.

Related