Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex and parseInt

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?

like image 425
Jayne Mast Avatar asked Oct 18 '11 10:10

Jayne Mast


People also ask

What is parseInt JavaScript?

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 .

What is JavaScript regex?

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.

Does parseInt throw error JavaScript?

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.

What is ?: In regex?

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.


2 Answers

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.

like image 96
Felix Kling Avatar answered Sep 28 '22 05:09

Felix Kling


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

like image 22
Matt Avatar answered Sep 28 '22 05:09

Matt