Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of PHP's " .= " in Javascript, to add something to a variable..?

In PHP you can do:

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

The output is: Hello world!

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

like image 339
pnichols Avatar asked Dec 02 '22 05:12

pnichols


2 Answers

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.

like image 124
Ken Redler Avatar answered Dec 03 '22 17:12

Ken Redler


The PHP concatenation operator is .

The Javascript concatenation operator is +

So you're looking for +=

like image 44
Chad Birch Avatar answered Dec 03 '22 18:12

Chad Birch