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
Related videos on Youtube
Comments
-
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 ?