将多行文本存储在JavaScript变量中

时间:2010-06-22 04:53:38

标签: javascript

用于在javascript变量中存储多行文本;

我正在使用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>

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

4 个答案:

答案 0 :(得分:3)

可悲的是,它有点烦人,因为你不能这样做。你必须这样做:

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

或者,使用类似的技巧,

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

答案 1 :(得分:1)

使用\n打破该行。

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

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

 <script> 
  bar = '<?php print $foo;?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>

如果您要将文字输出到浏览器,则必须使用<br />而不是\n

更多信息:

http://www.c-point.com/javascript_tutorial/special_characters.htm

答案 2 :(得分:1)

来自this answer<?php echo json_encode($foo); ?>(PHP&gt; = 5.2)

答案 3 :(得分:0)

试试这个

var JsString = "<?php 
echo str_replace(array("\n","\r","\r\n"),'','YOUR 
MULTI LINE 
STRING');?>";