Jayne Mast
Jayne Mast

Reputation: 1487

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?

Upvotes: 11

Views: 3910

Answers (3)

paulslater19
paulslater19

Reputation: 5917

Note that if you have more than one grouping, you can do something like:

"p-622-5350".replace(/p-(\d+)-(\d+)/, function (match, g1, g2) { 
    return "p-" + (+g1 * 10) + "-" + (+g2 *10); 
});

(note the extra parameters in the function)

Upvotes: 0

Matt
Matt

Reputation: 75317

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816522

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.

Upvotes: 17

Related Questions