store multi-line text in a JavaScript variable

11,186

Solution 1

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

Solution 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

Share:
11,186

Related videos on Youtube

Sourabh
Author by

Sourabh

Web developer , working for six years in LAMP stack

Updated on April 25, 2022

Comments

  • Sourabh
    Sourabh about 2 years

    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 ?