Easy Approach: Pass a PHP string to a JavaScript variable (and escape newlines)

Javascript Nov 13, 2022


How may a PHP string be most simply encoded for output to a JavaScript variable?

We have a PHP string that contains quotation marks and newlines. The contents of this string must be placed in a JavaScript variable.


Use json_encode()

  var newVar = <?php echo json_encode($varValue); ?>;

It requires:

  • PHP 5.2.0 or greater
  • $varValue encoded as UTF-8 (or US-ASCII)



Anurag Deep

Logical by Mind, Creative by Heart