Display variable content in Javascript that has quotes

Asked

Viewed 201 times

1

I have an application that reads in ajax a Mysql database, which in it is written a normal content (without escaping) with multiple words between double quotes, single or single quotes.

This content goes to a variable, ex:

conteúdo que está no banco de dados...= Quantos litros d'água está "sujo"

wVar = conteúdo acima

I have to show this by concatenating with another text, like:

alert("texto = "+wVar);

It’s like I’m trying to show off "texto = "+"Quantos litros d'água está "sujo""

Ai gives error, logically because the double quotation marks of the word "dirty" are not escaped.

How can I display these phrases correctly without knowing exactly what content will be loaded from the database in the variable?

Note: In the display the word "dirty" needs to be displayed with double quotes, as it is part of the correct content of the text.

3 answers

0

You can use inverted quotes, example:

alert(`Início do texto, agora a variável:${wVar}`)
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

0

Replace the contents coming from the bank by escaping the double quotes

var wVar = "Quantos litros d'água está \"sujo\"";

alert("texto = "+wVar);

0


You can put the return of the direct database in the Javascript variable between quotes (double or single) and use the method addslashes PHP that will escape the necessary quotes:

<script>
wVar = "<?=addslashes($texto_vindo_do_banco?>";
alert("texto = "+wVar);
</script>
  • $texto_vindo_do_banco = ????

  • Yes, from a query.

  • yes, I know, how to start this variable $texto_vindo_do_banco = ?????

  • Could be $row['texto']), of $row=mysqli_fetch_array($query)

Browser other questions tagged

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