[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


Line breaks and strings in dynamic javascript code

Posted on 2006-06-19
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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:
http://www.experts-exchange.com/Web/Q_21887155.html     Web Development: print php variable with javascript

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

(Ref: http://www.codeguru.com/forum/archive/index.php/t-350597.html, http://javascript.programmershelp.co.uk/scrolltext.php
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

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

Any way around this?

Assisted Solution

shaggy_the_sheep earned 600 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 600 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 1000 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:
http://www.codeguru.com/forum/archive/index.php/t-350597.html  "regular expressions/replace"
http://javascript.programmershelp.co.uk/scrolltext.php "Scrolling Textarea"
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace -->
<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 400 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…

650 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