I'm attempting to set up a script to concatenate some variables inside a string if they exist, in order to place the appropriate metadata tags into a rendered HTML document.
My concatenation code is:
data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";
I'm trying to add if
statements like the following into it (between the first and second items):
if (typeof metadata_title !== "undefined") {
"<title>" + metadata_title + "</title>\n"
}
if (typeof metadata_author !== "undefined") {
"<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n"
}
if (typeof metadata_date !== "undefined") {
"<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"
}
But I can't add any of these statements directly into the concatenation code (it throws an error: Unexpected token (
).
How best would I go about adding statements such as these into my concatenation string?
I might do something a little different (a little more akin to templating), mainly because I hate concatenated HTML done with Javascript:
Sure, there's a very small amount of additional overhead, but to me, it's way more readable.
Build up the entire document into an array, then join with a
"\n"
at the end. (The rationale for this is of course to not have lots of new lines scattered all about! And if you are on IE7 or less,Array#join
is considerably faster than repeated string concatenation.)Code here: http://jsfiddle.net/ZCbCZ/
UPDATE I forgot to include the "paras" in the first fiddle. The code with the paras is here: http://jsfiddle.net/U8325/1/
For those not wishing to click through and try it out, here is the script:
I'd use a ternary operator:
I liked the readability of Demian Brecht answer, but I would only change the string for a regex instead, because the replace() function only replaces the first match (see more here: JavaScript .replace only replaces first Match)