views:

29

answers:

2

The following does not work:

var js_str= '<?php echo $str_from_server; ?>';

The problem is that, $str_from_server can contain any characters. If it contains single quotes or line breaks or others, the above code will break. And I do not have access to the server-side code. What's the easiest way to "escape" the contents of $str_from_server into a javascript string, and then it can be restored later?

A: 

I would do:

var js_str= '<?= addslashes($str_from_server); ?>';

or:

var js_str= '<?= str_replace("'", "\'", $str_from_server); ?>';
J.Milly
+1  A: 

Since you are echoing that variable to your JavaScript code directly, you could use the json_encode function:

var js_str = <?php echo json_encode($str_from_server); ?>;

It will safely escape quotes for you, e.g.:

<?
  $str ='"\'"\'"\'"';
  echo  json_encode($str); // "\"'\"'\"'\""
CMS
If you're in a `<script>` element (which is likely for PHP), add the $options argument `JSON_HEX_TAG` to avoid `</` in the string ending the block.
bobince