Line breaks and strings in dynamic javascript code

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?
Who is Participating?
callrsConnect With a Mentor Commented:
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>
Khanh DoanSenior DeveloperCommented:
noteText = "\n";
I think the line break must be in " ".
aaron_karpAuthor Commented:
I don't understand what you're suggesting.
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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 />");}

aaron_karpAuthor Commented:
But then the <br/> tags show up inside the textarea :-/

Any way around this?
shaggy_the_sheepConnect With a Mentor Commented:

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.

aaron_karpAuthor Commented:
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.
shaggy_the_sheepConnect With a Mentor Commented:

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


Hold on, I found the answer. Back in <30 minutes.
Michel PlungjanConnect With a Mentor IT ExpertCommented:
'quickDiscardChanges(" + noteID + ",unescape(\"<? echo urlencode(noteText); ?>\"))'

Michel PlungjanIT ExpertCommented:
or have the php urlencode the ajax response and just do

'quickDiscardChanges(" + noteID + ",unescape(\""+ noteText +"\"))'
aaron_karpAuthor Commented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.