function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
avaragadoavaragado 

Escaping newlines in merge fields

I've got a multi-line field and I want its value in a JavaScript variable. I would like to avoid unnecessary network requests.

var value = "{!Foobar.field}";

Doesn't work as it's a multi-line field and JavaScript doesn't support literal strings with unescaped newlines. I tried this:

var value = "{!SUBSTITUTE(SUBSTITUTE(Foobar.field, "\n", "\\n"), "\r", "\\r")}";

The documentation is silent on escape sequences in strings, but \" works in SUBSTITUTE so I rashly assumed that the standard set of escape sequences would all work. But they don't; SUBSTITUTE apparently hasn't heard of \n and \r.

I've tried \012, \x0a and \u000a and get syntax errors for my trouble. Is there a way of doing what I want?
gsickalgsickal

instead of referencing the merge field in your scontrol as a variable, you will need to include a dummy html form in your control with the value there as described below.  this has been in several previous posts but i coulnd't find them so i just reproduced what was in them below:

make the field with carriage returns available to the script by putting it in an html form field:

<body onload="initPage()" class="home  editPage">
<div id="divMain"><h1>Please wait...</h1></div>
<div id="gOppDescription" style="position:absolute; visibility:hidden">{!Opportunity.Description}</div>
<form name="dummy" method="post">
<textarea id="gOppDescriptionTA" name="gOppDescriptionTA" style="visibility:hidden">
{!Opportunity.Description}
</textarea>
</form>
</body>


to refer to the field, use the following syntax:

var opp = new sforce.SObject("Opportunity");
opp.Id = id;
opp.Description = document.dummy.gOppDescriptionTA.value;

avaragadoavaragado
Yes, I thought of that. But Salesforce doesn't know to entity-encode the content - so a value that includes something HTML might want to interpret (such as "<" or "&") could cause undesired behaviour. In my application that's not something I can rule out.

I can, of course, escape those myself using nested SUBSTITUTEs. But I'm really surprised that a web-oriented application like Salesforce doesn't include basic, trivial-to-implement functionality for encoding field values for the web.

Incidentally I've posted an idea about this: Functions for entity encoding, URI encoding, JSON strings.

To illustrate how annoying this problem is, the ideas portal itself screwed up rendering of my perfectly encoded examples. (The preview was fine; it was only after I confirmed the post after reviewing possible duplicates that it displayed wrongly.)
EMHDevEMHDev
gsickal, Thanks very much for this.  I was stuck on this same problem and your solution has worked for me.

Erica