-1

In php I can have something like this:

$animal = 'horse';

$animal += ', tigers';

then the value of animals would be "horse, tigers". How do I do this type of variable concatenation in JavaScript?

Rafel
  • 1

4 Answers4

1
var szTest = "";
szTest += "One";
szTest += ", Two";
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • 2
    I want to downvote your hungarian (but I won't this time). Not only is hungarian out-dated in the first place, but javascript doesn't use zero-terminated strings, and thus your sz prefix is wrong. – Joel Coehoorn Dec 26 '10 at 01:51
  • @Joel, Systems Hungarian is outdated. Apps Hungarian can sometimes be useful. Another problem with this answer (and the question) is that this *isn't* how you do it in PHP. – Matthew Flaschen Dec 26 '10 at 01:55
  • @Joel agree completely, the sz makes every variable name look like some Hungarian guy's name. Ugh. – Rafe Kettler Dec 26 '10 at 02:01
  • And for the hungarian notation stuff Going thru this post: http://stackoverflow.com/questions/198825/best-way-to-get-rid-of-hungarian-notation – Chandu Dec 26 '10 at 02:28
1

In Javascript you can use the + to concatenate strings like so,

'horse' + ', tigers';

In PHP the string concatenation operator is .. So, your example should be:

$animal = 'horse';

$animal .= ', tigers';
Russell Dias
  • 70,980
  • 5
  • 54
  • 71
  • You can also use `+=` with roughly the expected effect (either way a new string is created). – Matthew Flaschen Dec 26 '10 at 01:51
  • @Matthew Flaschen Yes you can. The 'official' concatenation operator is the `.` as per the documentation. However, I will edit my post to reflect this. – Russell Dias Dec 26 '10 at 01:56
  • I wasn't clear. I meant you can use `+=` in **JavaScript**. If you do so in PHP, it will fail the same way `+` does (PHP will coerce the string to 0). – Matthew Flaschen Dec 26 '10 at 02:25
  • @Matthew Flaschen Oops, misinterpreted that. I should have tested it out anyway. Thanks for clearing it up. – Russell Dias Dec 26 '10 at 06:04
1

Surprise:

'horse' + ', tigers'; // 'horse, tigers'

Now read a good tutorial before asking a thousand more questions:
https://developer.mozilla.org/en/JavaScript/Guide

Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
0
var $animal = 'horse';

$animal += ', tigers';
user113716
  • 318,772
  • 63
  • 451
  • 440