I have a JavaScript regex to match numbers in a string, which I to multiply and replace.
'foo1 bar2.7'.replace(/(\d+\.?\d*)/g, parseInt('$1', 10) * 2);
I want it to return 'foo2 bar5.4'
but it returns 'fooNaN barNaN'
What am I doing wrong here?
Description. The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
RegExp ObjectA regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.
parseInt method as a parameter. The method throws an error if the string cannot be parsed into an integer. Note, that the code within the catch block is executed only if an exception is thrown. Let's make our integer parser a bit more useful.
It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.
parseInt('$1', 10) * 2
is executed first and its result is passed to replace
. You want to use a callback function:
'foo1 bar2.7'.replace(/(\d+\.?\d*)/g, function(match, number) {
return +number * 2;
});
Furthermore, parseInt
will round down any floating point value, so the result would be "foo2 bar4"
. Instead you can use the unary plus operator to convert any numerical string into a number.
You are passing the result of parseInt('$1', 10) * 2
to the replace
function, rather than the statement itself.
Instead, you can pass a function to replace
like so:
'foo1 bar2.7'.replace(/(\d+\.?\d*)/g, function (str) {
return parseInt(str, 10) * 2;
});
For more info, read the MDC article on passing functions as a parameter to String.replace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With