Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle newlines in Javascript? (from PHP)

I have code like this:

<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>

Where $txt is a PHP variable that can contain newlines like this:

line1
 line2 hello world

Which would end up like this:

var out="line1
 line2 hello world";

Which will cause a Javascript error, of course.

What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>

like image 985
Zeno Avatar asked Nov 24 '10 19:11

Zeno


People also ask

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

Can we use \n in PHP?

Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

Which function is used to automatically convert newlines into break tags?

The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.


3 Answers

Most of these don't work for me. Normally, I'd use json_encode like

    <?php
        $MyVar = json_encode($MyVar);
    ?>
    <javascript language='javascript'>
        MyVar = <?php echo $MyVar; ?>

But for a quick fix you can just break a line like this: Pay attention to the double quotes.

    <?php
    $MyVar = "line one here
              then line two here


              finally line five here";

    //** OR

    $MyVar = $MyVarA . 
    "

    " 
    . $MyVarB;

    ?>
    <HTML>
    <HEAD>
    <javascript language='javascript'>
    Myvar = "<?php echo $MyVar; ?>";

. . .

like image 95
MAtkins Avatar answered Oct 14 '22 00:10

MAtkins


$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );

should replace newlines. Don't do it this way.

This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:

$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";

json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.

like image 25
zzzzBov Avatar answered Oct 13 '22 23:10

zzzzBov


you can add a \ at the end of a line to create a multi line String

var out="line1 \
 line2 hello world";
like image 26
Daniel Avatar answered Oct 14 '22 01:10

Daniel