How to handle newlines in Javascript? (from PHP)

2019-01-12 03:49发布

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>

6条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-12 04:34

You can use str_replace to convert line breaks into a different character (in this case, perhaps a space, but it depends how you want the output to show up)

$out = str_replace("\n", '\n', $in);
查看更多
放荡不羁爱自由
3楼-- · 2019-01-12 04:42

I tried this and it worked well.

<?php
    echo '<script type="text/javascript">';
    $txt = "line1 \\n line2 hello world";
    echo 'var out="'.$txt.'";';
    echo '</script>';
?>

I am using PHP 5.3

查看更多
干净又极端
4楼-- · 2019-01-12 04:43
$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.

查看更多
我命由我不由天
5楼-- · 2019-01-12 04:43

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

. . .

查看更多
Viruses.
6楼-- · 2019-01-12 04:44

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

var out="line1 \
 line2 hello world";
查看更多
神经病院院长
7楼-- · 2019-01-12 04:46
$content = str_replace( "\\n", "\\\\\\n", $content );

Result:

var a = "Hello \
World"
查看更多
登录 后发表回答