How to quote a javascript string

Asked

Viewed 2,479 times

-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 the Storage site.

  • 2

    What is the relation of the problem with local Storage?

  • When I do Let parser = new Domparser(); xmlDoc=parser.parseFromString(localStorageRow,"text/xml"); does not recognize the string

2 answers

6

The easiest is for you to use strings template:

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

The fact of using the grave accent allows you to use quotes inside the string and mainly allows you to interpolate with variables.

Another way would be to properly escape the quotation marks or use simple quotation marks.

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

// Usando aspas simples
xmlRowString += '<imagem class="'+r+'"></imagem>';
  • of all error...

  • 2

    @Yunrin127 but that is what answers your question. To say that error does not help anything, we need information. What you did, how you did it, why you did it, what the error message was, how you executed it, etc. However, this should probably be another question, because you asked only how to add the quotes - and this was done.

2

Just put " (Slash and Quotes) inside the quotes so that it is identified as a character.

 colors = ["\"red\"","\"green\""];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.