A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Newline character “n” problems in a Javascript string + PHP

I have just spent an hour an a half trying to figure out why the newline character “n” caused an error in my Javascript. I am posting this because I have been unsuccessful in finding a solution to this problem.

I am basically trying to display a newline character inside a textbox.

<?php
$var = "This is the first line. n This is the second line.";
?>
 
<textarea id="mytext"></textarea>
 
<script type="text/javascript" language="javascript">
    $(document).ready( function () {
        $('#mytime').val('<?=$var?>')
    });
</script>

The error I get above is:

unterminated string literal

When I view the source code, I have this:

$('#mytime').val('This is the first line.
This is the second line.');

Using str_replace() to remove the “n”
Apparently, this does not work.

$temp = str_replace("n","",$var); //does not work

Has anyone experienced this issue?

Thanks,
Wenbert

UPDATE:
I found this in Stackoverflow.

The solution, use json_encode().

<?php
$var = "This is the first line. n This is the second line.";
?>
 
<textarea id="mytext"></textarea>
 
<script type="text/javascript" language="javascript">
    $(document).ready( function () {
        $('#mytime').val('<?=json_encode($var)?>')
    });
</script>

There. Who would have thought of that?

This entry was posted in General and tagged , , . Bookmark the permalink.

One Response to Newline character “n” problems in a Javascript string + PHP

  1. Rimmi says:

    Hi,

    We are looking for blogroll exchange, which will mutually help us to get better rank in major search engines. We will add your site on http://www.bpooutsourcingindia.com, so send your site details as soon as possible.

    Please insert our site link on your website, our website details are mentioned as below.
    Title: Outsource Web Development
    URL: http://www.topprojectshub.com/webdesign-development.html

    Looking for your prompt response.

    Regards,
    Rimmi Sharma
    Internet Marketer

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>