views:

125

answers:

6

In PHP you can do:

$myvar = "Hello";
$myvar .= " world!";
echo $myvar;

The output is: Hello world!

How can I do this in Javascript/jQuery..?

+9  A: 
var a = 'Hello';
    a += ' world';
alert(a);

You'll get a dialog with "Hello world".

Be careful with this, though:

var a = 3;
    a += 'foo';

Result: 3foo. But:

var a = 3;
    a += 4;
    a += 'b';

You'll get an interesting result, and probably not the one you expect.

Ken Redler
+1 for pointing out the danger inherent in the overloaded `+` operator
Kip
interesting result = '7b'
Evan Carroll
interesting result looks pretty predictable to me...
serg
+4  A: 

The PHP concatenation operator is .

The Javascript concatenation operator is +

So you're looking for +=

Chad Birch
+2  A: 

In JavaScript the string concatenation operation is + and the compound string concatenation and assignment operator is +=. Thus:

var myvar = "Hello";
myvar += " world!";
Gumbo
+1  A: 

Got it.

I was doing this:

var myvar = "Hello";
var myvar += " world!";
var myvar += " again!";

I guess the multiple var was my problem...

Thanks all.

pnichols
+1  A: 

+ is the String concatenation operator in Javascript. PHP and Javascript, both being loosely-typed languages, deal with conflicts between addition and concatentation in different ways. PHP deals with it by having a completely separate operator (as you stated, .). Javascript deals with it by having certain rules for which operation is being performed. For that reason, you need to be aware of whether your variable is typed as a String or a Number.

Example:

  • "1" + "3": In PHP, this equals the number 4. In JavaScript, this equals "13". To get the desired 4 in Javascript, you would do Number("1") + Number("3").

The basic idea in Javascript is that any two variables that are both typed as Numbers with a + operator in between will be added. If either is a string, they will be concatenated.

Renesis
A: 

var a="Hello"; a+="world !";

output: Hello world!

Rahul