How do I combine 2 javascript variables into a string
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
warning! this does not work with links.
var variable = 'variable', another = 'another';
['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');
Use the concatenation operator +
, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;