store multi-line text in a JavaScript variable

Sou*_*abh 6 javascript

Ho to store multiline text in a javascript variable;

我正在使用PHP为javascript变量赋值.

请参阅下面的示例代码

<html>
 <head>
 <title> New Document </title>
 <?php

  $foo = " this is a 
               multiline statement";
 ?>

 <script> 
  bar = '<?php print $foo;?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我不想丢失任何空白字符.这怎么办?

Mon*_*der 5

Sadly, it's a bit annoying as you can't do it that way. You'll have to do it like this:

var str = [
    "Hello, this is a       \n"
    "multiline\n",
    "       string."
].join("");
Run Code Online (Sandbox Code Playgroud)

Or, using a similar trick,

var str = [
    "Hello, this ",
    "     is a multiline ",
    "string separated by new lines ",
    " with each array index"
].join("\n");
Run Code Online (Sandbox Code Playgroud)


小智 1

来自这个答案<?php echo json_encode($foo); ?>(PHP >= 5.2)