Search code examples
javascriptvariablesquotesdouble-quotes

How to store a string in a JavaScript variable that has Single Quotes and Double Quotes?


I need to create a variable storing dynamically generated HTML content. The html content in the String returned from PHP might have single or double quotes.

html_content=<?=$string;?>;

The string may have double quotes like this:

<span id="something">something else</span>

or single quotes like this:

<span id='something'>something else</span>

Then, how can I correctly save the string in javascript? I can't use single quotes or double quotes.


Solution

  • You could save that kind of string by modifying it on the server side before output, like this:

    html_content = "<?=addslashes($string);?>"
    

    The method addslashes($string) would then escape any double quotes at runtime before feeding it to the JavaScript variable.