Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a javascript equivalent of .= for self concatenating?

Tags:

javascript

Rather than doing

my_var = my_var+'extra string';

is there a shorthand method like .= in php?

like image 353
Haroldo Avatar asked Mar 17 '10 12:03

Haroldo


People also ask

How do I concatenate a string with itself?

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.

How do you concatenate in JavaScript?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.

How do I concatenate two fields in JavaScript?

concat() function is used to join two or more strings together in JavaScript. Arguments: The arguments to this function are the strings that need to be joined together. The number of arguments to this function is equal to the number of strings to be joined together.

What Concat function will do in JavaScript?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


2 Answers

Use +=

var s = 'begin';
s += 'ning';
like image 178
npup Avatar answered Sep 23 '22 12:09

npup


Performance Tip (note — this advice is valid for IE6, but it's no longer worth worrying about in 2014)

If you're writing some Javascript code to build up a long string (say, a fairly big block of HTML, or a long parameter list for an ajax request), then don't get in the habit of doing this:

var longString = "";
for (var i = 0; i < someBigNumber; ++i) {
  if (i > 0) longString += "<br>" + whatever;
  longString += someMoreStuff();
}

As the longString gets longer and longer, Internet Explorer will puff harder and harder on each iteration of the loop. Even when someBigNumber isn't really that big, the performance of that loop can be really terrible.

Luckily, there's an easy alternative: use an array:

var accumulator = [];
for (var i = 0; i < someBigNumber; ++i) {
  accumulator.push(someMoreStuff());
}
var longString = accumulator.join("<br>" + whatever);

Way, way faster in Internet Explorer than repeated string appends.

like image 24
Pointy Avatar answered Sep 22 '22 12:09

Pointy