Concatenate Variables Containing Numbers

Concatenate Variables Containing Numbers

I need to know how to concatenate variables containing numbers, that is, string them together one after the other. Every method I know simply adds the various numbers together and spits out the sum.


You’re right?if you simply try to add the variables together using the plus (+) operator you’ll get the values added numerically. For example, given that:

var a = 5;var b = 10;var c = 999;

This code correctly displays the value 1014:

alert (a + b + c);

What you want to do is to trick the JavaScript interpreter into thinking that you want a string result, not a numeric one. An easy way to do that is to include a string constant as one of the items being added. This results in the variables being treated as strings instead of numerals. In addition, if the string you throw into the mix is an empty one it won’t disrupt what you’re trying to accomplish. For example, this code displays 510999 as you’d expect:

alert ("" + a + b + c);


Share the Post: