Store multiline text in JavaScript variable

Ho for storing multi-line text in a javascript variable;

I am using PHP to assign a value to a javascript variable.

Please see 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 do not want to lose space characters. How can I do that?

+6
javascript
source share
4 answers

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

+1
source share

Unfortunately, this is a little annoying as you cannot do this. You will need to do this as follows:

 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"); 
+3
source share

Use \n where you want to split the string.

 <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 display text in a browser, you will need to use <br /> rather than \n .

Additional Information:

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

+1
source share

try it

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

All Articles