如何在使用带有textarea文本的jQuery追加时处理回车

I have text that comes from a textarea where the user might have legitimate carriage returns.

If the text has a carriage return that I want to preserve, how do I do that with this exact jQuery append example.

I'm generating this html code and it will break if the variable $text has carriage returns in it.

Example:

$(".inner").append( "<textarea><?php echo $text; ?></textarea>" );

So if:

$text = "Cat

Dog";

Then I get this and it causes an error.

$( ".inner" ).append( "<textarea>Cat

Dog</textarea>" );

What can I do to preserve the carriage returns when append creates this textarea html?

You need to make sure that the php value gets passed to javascript correctly. The best way to do that, is to encode it as json. Then you can use for example .val() to set the value of your element:

var myText = <?php echo json_encode($text); ?>;
$( ".inner" ).append( $('<textarea>').val(myText) );

Use addcslashes function, it allows to encode carriage returns as (which is compatible with javascript).

$(".inner").append( "<textarea><?php echo addcslashes($text,"
"); ?></textarea>" );

Function reference

Update

I decline my answer for the @jeroen 's answer. In case you have an old PHP version which doesn't support json_encode you can use Chengings' function

function escape_javascript_string($str){
    // if php supports json_encode, use it (support utf-8)
    if (function_exists('json_encode')) {
        return json_encode($str);
    }
    // php 5.1 or lower not support json_encode, so use str_replace and addcslashes
    // remove carriage return
    $str = str_replace("", '', (string) $str);
    // escape all characters with ASCII code between 0 and 31
    $str = addcslashes($str, "\0..\37'\\");
    // escape double quotes
    $str = str_replace('"', '\"', $str);
    // replace 
 with double quotes
    $str = str_replace("
", '
', $str); 
    return $str;
}

All you need to do is the following:

PHP:

$cleaned = str_replace("
", "\
", $text);

JS:

$(".inner").append("<textarea><?= $cleaned ?></textarea>");

This example from php.net documentation is working for me now. From Replace carriage return in an email

// Order of replacement
$order   = array("
", "
", "");
$replace = '<br />';

// Processes 
's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $text);

The "br" tag is working inside of the textarea, though I though it wouldn't.