9
I started learning Python and was told that I shouldn’t concatenate the strings with , but use the method .format(). And in Javascript it is correct to use + or , to concatenate the strings or there is a more recommended and more used way?
9
I started learning Python and was told that I shouldn’t concatenate the strings with , but use the method .format(). And in Javascript it is correct to use + or , to concatenate the strings or there is a more recommended and more used way?
16
You can also use "template string" for this:
var str1 = 'hello';
var str2 = 'world';
var res = `${str1} ${str2}`;
In this case where there are only 2 strings, it doesn’t make much sense to use, but in larger concretions, it is very interesting.
Template string is part of ES6/ES2015, some older browsers may not support.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings http://wesbos.com/javascript-template-strings/
to not even there with old browsers, to equal the Whatsapp for old cell phones.
I just loved these template strings.
12
There’s nothing ugly or wrong in making a simple str1+" "+str2. It can be used without problems. It is simple and efficient. It has no technical reasons to choose a shape, it is just style.
Although ugly depends on taste, I find any other ugly form, longer and even less intuitive when it strikes the eye fast. Pick one and be consistent, don’t keep changing the shape.
There could be problems if you make many concatenations within a loop, but even this JS optimizes, so up to the use of str += str2 is fitting in a loop.
7
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);
Upshot: Hello world!
Reference: https://www.w3schools.com/JSREF/jsref_concat_string.asp
Another way, with +:
var res = str1+str2;
Which way Voce recommends, Concat or simply the +?
Browser other questions tagged javascript string
You are not signed in. Login or sign up in order to post.
Concatenate in what context? Pure and simple, two strings?
– Maniero
That’s all. It’s just that I started to think this is ugly: str1+" "+str2.
– user83428
@bigown I would know if there is any place on the site to post questions half out of scope like this?
– user83428
I wouldn’t say she’s out of scope, maybe too simple :) So it’s right here.
– Maniero