6

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 ?

Sourabh
  • 4,545
  • 11
  • 39
  • 45
  • Duplicate of http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines it seems –  Jun 22 '10 at 04:55

4 Answers4

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

Or, using a similar trick,

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

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
  • 377,238
  • 77
  • 533
  • 578
1

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

Community
  • 1
  • 1
0

try this

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