Rather than doing
my_var = my_var+'extra string';
is there a shorthand method like .= in php?
In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.
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.
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.
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.
Use +=
var s = 'begin';
s += 'ning';
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With