3

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.

1
  • 2
    Just as a side note: it is recommended you always use <?php and ?> instead of <?= and ?> for compatibility. The former is supported everywhere, the latter not necessarily. Just for info. Commented Sep 13, 2012 at 20:39

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Well you could always use JavaScript's escape function to serialize your string before storing it. That'll work.

I think the bigger issue here, though, is that single quotes are actually not valid the way you're attempting to use them in your id attribute like that (per the HTML spec). It always has to be double quotes. If the code that that's coming from isn't under your control, then there's not much you can do, it's just broken; but if it is under your control, you should fix it too.

1 Comment

escape is now deprecated
0

Use json_encode to pass almost any variable from PHP to JavaScript.

html_content=<?=json_encode($string)?>;

In the case of a string, it will automatically add quotes and any necessary escaping.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.