Oliver Brodersen Oliver Brodersen - 9 months ago 42
HTML Question

Javascript adding numbers as if they were a string

I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.

I have a cookie called

, and when I want this value I use a script I found by Jeffery To that looks like this:

function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];

After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this:
value + 1 = 10
. Simple math. However it gives me this
. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?

After reading the comments I learned that i needed to put my
inside a
. So i simply modified the funtion to say:

function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);

Answer Source

The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.

The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.

To force a string containing a number character into a number, you can use parseInt() and parseFloat():

 var result = parseInt(value, 10) + 1;

Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.

Also note that both parseInt() and parseFloat() stop after finding the first valid characters that could be treated as numbers. So, in a string like this: "Scott7Marcy9", you would only get the 7.