Display Javascript variable content that has quotation marks

1

I have an application that ajax reads a MySQL database, which contains a normal (non-escaped) content with several words in double quotes, single or single quotes.

This content goes to a variable, eg:

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

wVar = conteúdo acima

I have to display this concatenating with another text, type:

alert("texto = "+wVar);

It's how I wanted to display "texto = "+"Quantos litros d'água está "sujo""

There is an error, logically because the double quotation marks of the word "dirty" is 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 view the word "dirty" needs to be displayed with the double quotes as it is part of the correct content of the text.

    
asked by anonymous 14.02.2018 / 20:30

3 answers

0

You can put the direct return of the bank in the JavaScript variable between quotation marks (double or single) and use the addslashes of PHP that will escape the necessary quotation marks:

<script>
wVar = "<?=addslashes($texto_vindo_do_banco?>";
alert("texto = "+wVar);
</script>
    
15.02.2018 / 00:20
0

You can use inverted quotation marks, for example:

alert('Início do texto, agora a variável:${wVar}')
    
14.02.2018 / 20:52
0

Give the content that comes from the database by replacing the double quotation marks

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

alert("texto = "+wVar);
    
15.02.2018 / 00:16