Concatenating strings with `if` statements in JavaScript

木川 炎星 picture 木川 炎星 · Sep 8, 2011 · Viewed 39.3k times · Source

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?

Answer

bluish picture bluish · Sep 8, 2011

I'd use a ternary operator:

data = "<html>\n"
     + "<head>\n" 
     + ( typeof metadata_title  !== "undefined" ?  "<title>" + metadata_title + "</title>\n"                             : "" )
     + ( typeof metadata_author !== "undefined" ?  "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
     + ( typeof metadata_date   !== "undefined" ?  "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"     : "" )
     + "</head>\n"
     + "<body>\n"
     + "\n"
     + paras.join("\n\n")
     + "\n"
     + "\n"
     + "</body>\n"
     + "</html>"
;