Asked • 05/28/19

Pass a PHP string to a JavaScript variable (and escape newlines)?

What is the easiest way to encode a PHP string for output to a JavaScript variable? I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable. Normally, I would just construct my JavaScript in a PHP file, &#224; la: <script> var myvar = "<?php echo $myVarValue;?>"; </script> However, this doesn't work when `$myVarValue` contains quotes or newlines.

1 Expert Answer


Stefan R. answered • 02/28/20

5.0 (625)

Senior PHP developer with 10+ years of experience

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.