Concatenating strings with `if` statements in JavaScript

后端 未结 5 762
眼角桃花
眼角桃花 2021-01-01 10:27

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

相关标签:
5条回答
  • 2021-01-01 10:43

    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.

    0 讨论(0)
  • 2021-01-01 10:53

    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>"
    ;
    
    0 讨论(0)
  • 2021-01-01 10:55

    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);
    
    0 讨论(0)
  • 2021-01-01 11:03
    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>";
    
    0 讨论(0)
  • 2021-01-01 11:08

    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 : "");
    
    0 讨论(0)
提交回复
热议问题