Line breaks and strings in dynamic javascript code

Posted on 2006-06-19
Last Modified: 2012-06-21
I'm building an AJAX-based site where all the content is dynamically fetched and then written to the page. Only problem is, I'm not a javascript wizard.

In this particular problem, I'm trying to build a text area with a Gmail-style Save / Discard Changes option. This text area gets written to the page, dynamically by editing the innerHTML property of a blank container as follows:

// noteID and noteText are already retrieved by making an AJAX request
// to a PHP script. The PHP script returns the noteText variable with all
// html special characters encoded, so that the quotes won't be any trouble

var qv = $('noteQuickView' + noteID);

var newInnerHTML = "<br/><div style='margin-top:2px'><img src='images/buttons/blue_block/Save_and_Close.png' alt='Save and Close' onclick='quickSave(" + noteID + ")' /> <img src='images/buttons/blue_block/Discard_Changes.png' alt='Save' onclick='quickDiscardChanges(" + noteID + ",\"" + noteText + "\")' /></div>";

qv.innerHTML = newInnerHTML;

When the noteText variable does not contain any line breaks, everything works perfectly. But when there are line breaks and I press the "Discard Changes" button, I get a javascript error. Firefox / webdev toolbar says "Unterminated string literal" but I can't figure out why. Maybe the line break is splitting the javascript code, even though it's dynamic. Is there an easy way around this? Maybe some way to escape the line breaks without messing up the data that shows up in the textarea?
Question by:aaron_karp
  • 4
  • 3
  • 2
  • +2
LVL 10

Expert Comment

by:Khanh Doan
ID: 16940060
noteText = "\n";
I think the line break must be in " ".

Author Comment

ID: 16940081
I don't understand what you're suggesting.
LVL 30

Expert Comment

ID: 16940381
In any PHP variables, or in the final newInnerHTML variable, replace all "\n" and "\n\r" with "<br />", before using qv.innerHTML =

For a PHP script enclosed in Javascript:     Web Development: print php variable with javascript

For pure Javascript:
<script type="text/javascript">
function nToBR(myString){return myString.replace(/\n/g, "<br />");}

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.


Author Comment

ID: 16940403
But then the <br/> tags show up inside the textarea :-/

Any way around this?

Assisted Solution

shaggy_the_sheep earned 150 total points
ID: 16940481

I had this problem recently...

try replacing any '\n' with'\\n'
qv.innerHTML = newInnerHTML.replace(/\n/gi,"\\n"))

this is an example of what i had to do...
Original String:
document.write('<span onclick="alert(\'Hello\nWorld!\')">Hello</span>');

this produced an 'Unterminated string constant' error.

I then replaced the '\n' with '\\n' and this seemed to fix it.
document.write('<span onclick="alert(\'Hello\\nWorld!\')">Hello</span>');

Give it ago and let me know.


Author Comment

ID: 16940566
Hmm, that does fix the problem of the Javascript errors, but now the textarea shows "Testing Testing\n\nHello World!"

In other words, now the line breaks are escaped, so they're visible characters inside the textarea.

Assisted Solution

shaggy_the_sheep earned 150 total points
ID: 16940674

I think the problem lies in the fact that you are setting the textarea's innerHTML, rather than its value.

Would it be possible to move the 'Save and Discard' buttons to a div, and then locate the textarea within that sme div. You could then use:

qv.value = RetrievedValue

I believe this would work better, as the escaped '\n' should now appear as new lines.

I hope this makes sense


LVL 30

Expert Comment

ID: 16940932
Hold on, I found the answer. Back in <30 minutes.
LVL 30

Accepted Solution

callrs earned 250 total points
ID: 16941136
1) Enclose the textarea in a <FORM id="qvform"> tag.

2) Use:  self.document.forms['qvform'].elements['qv'].value=newInnerHTML
instead of:  qv.innerHTML = newInnerHTML;

3) Call the BRtoN function to convert all <BR> tags to "\n"

For a working example, save & open this file in a browser:

<!-- Textarea multi-line javascript example
      By Ravinder Singh, 2006-06-20  -->
<!-- With help from:  "regular expressions/replace" "Scrolling Textarea" -->
<script type="text/javascript">
// Convert to & from \n <--> <br />
function nToBR(myString){return myString.replace(/\n/g, "<br />");}
function BRtoN(myString){
      myString=myString.replace(/<br.*?>/ig, "\n");
      return myString;
function reset_(){
t="Line 1"
t+="<BR />Line 2"
t+="<BR>Line 3"
t+="<BR />Line 4"
//document.getElementById("qv").innerHTML=t  // Doesn't work for line breaks

//self.document.forms[0].elements[0].value=t          // But this does ~!

self.document.forms["qvform"].elements["qv"].value=t;  // Tested & works in IE, Opera, Firefox

//document.getElementById("qv").value=t        // Also works in all three

<body onload="setTimeout('reset_()', 2000);">
<FORM NAME = "qvform" ACTION = " ">
<textarea id="qv" rows=20>
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 100 total points
ID: 16941541
'quickDiscardChanges(" + noteID + ",unescape(\"<? echo urlencode(noteText); ?>\"))'

LVL 75

Expert Comment

by:Michel Plungjan
ID: 16941568
or have the php urlencode the ajax response and just do

'quickDiscardChanges(" + noteID + ",unescape(\""+ noteText +"\"))'

Author Comment

ID: 16946125
I actually solved the problem in a different way altogether; Instead of trying to encode/escape the \n characters somehow, I simply removed the second argument from quickDiscardChanges() and then retrieve it manually from inside the function.

Still, a lot of you guys had some excellent ideas. Thanks.

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how would you interpret lines 3 36
how can i remove string values 2 29
how can i select 4 28
Help with removing item from Session Array 3 22
In my daily work (mainly using, I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now