Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Math processing
Expertise: Beginner
Oct 22, 1999

Concatenate Variables Containing Numbers

Question:
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.

Answer:

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);
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date