tags:

views:

52

answers:

3

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;?>';
  alert(bar);
 </script>
 </head>
  <body>
 </body>
</html>

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

A: 

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

Sarfraz
A: 

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

RC
A: 

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