Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like;

for (i=1;i<=2;i++){
    var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map, 
title:"title"+i,
icon: "image"+i
}); 
}

and later on I have

myLatlng1=xxxxx;
myLatlng2=xxxxx;
like image 862
Lenny Magico Avatar asked May 07 '11 17:05

Lenny Magico


People also ask

How do I concatenate a variable to a string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Does += work with strings JavaScript?

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.

What are the ways to join two strings in JavaScript?

The concat() method joins two or more strings. The concat() method does not change the existing strings. The concat() method returns a new string.

How do you concatenate strings and variables in node JS?

The concat() method concatenates a string argument to the calling string and returns a new string. In the examples below, we will take two strings and combine them using the concat() method. As you may have noticed, the concat() method takes a variable number of arguments.


2 Answers

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;
like image 95
Lightness Races in Orbit Avatar answered Sep 22 '22 08:09

Lightness Races in Orbit


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!
like image 28
Muneeb Avatar answered Sep 18 '22 08:09

Muneeb