开发者

store multi-line text in a JavaScript variable

Ho to store multiline text in a javascript variable;

I am using PHP to assign value to javascript variable.

Please see a SAMPLE code below

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

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

 <script> 
  bar = '<?php print $foo;开发者_Go百科?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>

I don't want to loose any white-space characters.How can this be done ?


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("");

Or, using a similar trick,

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


From this answer: <?php echo json_encode($foo); ?> (PHP >= 5.2)


Use \n where you want to break the line.

<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>

If you want to output the text to browser, you will have to use <br /> rather than \n.

More Info:

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


try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜