最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex and parseInt - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Oct 18, 2011 at 10:02 Jayne MastJayne Mast 1,4871 gold badge16 silver badges32 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

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

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)

发布评论

评论列表(0)

  1. 暂无评论