How to put quotation marks in a javascript string

-1

I have this code:

colors = ["red","green"]
let xmlRowString = "<imagens>";
for(let y = 0; y < this.colors.length; y++){
  let r = colors[y];
  xmlRowString += "<imagem class="+r+"></imagem>";
}
xmlRowString += "</imagens>";

This returns:

<imagens><imagem class=red></imagem> <imagem class=green></imagem></imagens>

What I need:

<imagens><imagem class="red"></imagem><imagem class="green"></imagem></imagens>

It's about local storage.

    
asked by anonymous 04.01.2019 / 11:52

2 answers

5

The easiest way is to use template strings :

xmlRowString += '<imagem class="${r}"></imagem>';

Using the severe accent allows you to use quotation marks inside the string and, in particular, allows you to interpolate with variables.

Another way would be to either escape the quotes or use single quotation marks.

// Escapando as aspas
xmlRowString += "<imagem class=\""+r"\"></imagem>";

// Usando aspas simples
xmlRowString += '<imagem class="'+r+'"></imagem>';
    
04.01.2019 / 12:22
2

Just put \ "(Bar and quotation marks) inside the quotation marks so that it is identified as a character.

 colors = ["\"red\"","\"green\""];
    
04.01.2019 / 12:26