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

Posted on: Oct 27, 2009 by wenbert

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?


Subscribe to comments Comment | Trackback |
Post Tags: , ,

Browse Timeline


Comments ( 1 Comment )

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

Rimmi added these pithy words on Nov 03 09 at 10:38 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!