CDATA-blocks work great for coding large blocks of HTML, or CSS, into strings. But, I can't figure out how to use a variable-value within one.
For example, consider this JavaScript code:
var FullName = "Friedrich Hayek";
var ProfileCode = (<><![CDATA[
<div id="BigHonkingChunkO_HTML">
...Lot's o' code...
Name: $FullName$
Birth: $Birthdate$
...Lot's o' code...
... $FullName$ ...
...Lot's o' code...
</div>
]]></>).toString ();
How do I get $FullName$ to render as "Friedrich Hayek" instead of "$FullName$"?
Note that there is more than one variable and each variable can be used a few times in the CDATA block.
Alternate code sample:
var UserColorPref = "red";
var UI_CSS = (<><![CDATA[
body {
color: $UserColorPref$;
}
]]></>).toString ();
Looking to set the color attribute to red.
Is it elegant enough ?
function replaceVars(content, vars)
{
return content.replace(/\$(\w+)\$/g, function($0, $1)
{
return ($1 in vars ? vars[$1] : $0);
});
}
ProfileCode = replaceVars(ProfileCode, {"FullName" : "Friedrich Hayek"});
In case associative keys don't really matter, you can always opt to use:
sprintf or vsprintf
EDIT
What about making the 2nd parameter optional ?
function replaceVars(content, scope) {
if (!scope || typeof scope != "object") {
scope = this;
}
return content.replace(/\$(\w+)\$/g, function($0, $1) {
return ($1 in scope ? scope[$1] : $0);
});
}
// example1
var FullName = "Friedrich Hayek";
ProfileCode = replaceVars(ProfileCode);
// example2
var vars = {"FullName" : "Friedrich Hayek"};
ProfileCode = replaceVars(ProfileCode, vars);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With