How to handle newlines in Javascript? (from PHP)

$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.

Leave a Comment