简体   繁体   中英

Concatenating strings with `if` statements in JavaScript

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'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>"
;
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>";

I might do something a little different (a little more akin to templating), mainly because I hate concatenated HTML done with Javascript:

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace("#title#", metadata_title != undefined ? metadata_title : "")
                   .replace("#author#", metadata_author != undefined ? metadata_author : "")
                   .replace("#date#", metadata_date != undefined ? metadata_date : "");

Sure, there's a very small amount of additional overhead, but to me, it's way more readable.

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 )

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace(/#title#/g, metadata_title != undefined ? metadata_title : "")
                   .replace(/#author#/g, metadata_author != undefined ? metadata_author : "")
                   .replace(/#date#/g, metadata_date != undefined ? metadata_date : "");

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:

// Not going to define metadata_author just to be saved by typeof :-)
var metadata_title = "Hello";
var metadata_date = "2011-09-07";

// Okay 3 paras for fun
var paras = ["<p>paragraph1</p>", "<p>paragraph2</p>", "<p>paragraph3</p>"];

data = ["<html>", "<head>"]

if (typeof metadata_title !== "undefined") {
    data.push("<title>" + metadata_title + "</title>");
}
if (typeof metadata_author !== "undefined") {
    data.push("<meta name=\"author\" content=\"" + metadata_author + "\"></meta>");
}
if (typeof metadata_date !== "undefined") {
    data.push("<meta name=\"date\" content=\"" + metadata_date + "\"></meta>");
}

data.push("</head>");
data.push("<body>");
paras.forEach(function (p) {data.push(p);});   // Requires ES5; use a for-loop if you don't have it
data.push("</body>");
data.push("<html>");
data = data.join("\n");
alert(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM