views:

120

answers:

2

I have a simple, but perplexing problem, with Math.

The following code will take a number from a string (usually contained in a span or div) and subtract the value of 1 from it.

.replace(/(\d+)/g, function(a,n){ return (+n-1); });

This works really well, except when we get below zero. Once we get to -1 we're obviously dealing with negative subtraction.

-1 - 1 = -0
-0 - 1 = --1

how can I avoid this? It's likely I've got a general problem with the math here.

+6  A: 

The problem is that your function is not treating "-1" as negative one - it's being treated as a hyphen followed by positive 1.

/(-?\d+)/g will capture a leading hyphen as well.

Anon.
+2  A: 

Your .replace(/(\d+)/g) isn't capturing the leading -. If you want your addition to be correct, you'll need something like /(-?\d+)/.

Seth