After scouring the CDATA spec, and this "CDATA Confusion" article, it seems that CDATA sections treat everything as pure text, except for character-data entities and the section end marker (]]>
). For example,
var x = $('<!DOCTYPE X[<!ENTITY foo "BAR">]><z> cc A &foo;</z>');
console.log ($(x, 'z').text() );
Yields: ]> cc A &foo;
So, there's no way to have variable substitution within a CDATA section. The best we can do is start and stop the sections, like so:
var FullName = "Friedrich Hayek";
var ProfileCode = (<><![CDATA[
<div id="BigHonkingChunkO_HTML">
...Lot's o' code...
Name: ]]></>).toString () + FullName+ (<><![CDATA[
...Lot's o' code...
</div>
]]></>).toString ();
console.log (ProfileCode);
-- which is obviously not acceptable.
Practical workaround:
It won't help anyone looking for a CDATA solution (which we now know is impossible, per the spec). But as we were just using CDATA as a method to generate a complex string, then we can clean the string up afterwards, per Ratna Dinakar's answer.
The function we ended up using is:
function sSetVarValues (sSrcStr, sReplaceList /* , Variable */)
/*--- function sSetVarValues takes a string and substitutes marked
locations with the values of the variables represented.
Conceptually, sSetVarValues() operates a little like sprintf().
Parameters:
sSrcStr -- The source string to be replaced.
sReplaceList -- A string containing a comma-separated list of variable
names expected in the raw string. For example, if
sReplaceList was "Var_A", we would expect (but not require)
that sSrcStr contained one or more "$Var_A$" substrings.
*Variable* -- A variable-length set of parameters, containing the values
of the variables specified in sReplaceList. For example,
if sReplaceList was "Var_A, Var_B, Var_C", then there better
be 3 parameters after sReplaceList in the function call.
Returns: The replaced string.
*/
{
if (!sSrcStr) return null;
if (!sReplaceList) return null;
var aReplaceList = sReplaceList.split (/,\s?/);
for (var J = aReplaceList.length-1; J >= 0; --J)
{
var zRepVar = new RegExp ('\\$' + aReplaceList[J] + '\\$', "g");
sSrcStr = sSrcStr.replace (zRepVar, arguments[J+2]);
}
return sSrcStr;
}
Sample use:
var AAA = 'first';
var BBB = 'second';
var CCC = 'third';
var Before = "1 is $AAA$, 2 is $BBB$, 3 is $CCC$";
var After = sSetVarValues (Before, "AAA, BBB, CCC", AAA, BBB, CCC);
console.log (Before);
console.log (After);
Yields:
1 is $AAA$, 2 is $BBB$, 3 is $CCC$
1 is first, 2 is second, 3 is third