Concatenating strings with `if` statements in JavaScript

后端 未结 5 787
眼角桃花
眼角桃花 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: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 = ["

    paragraph1

    ", "

    paragraph2

    ", "

    paragraph3

    "]; data = ["", ""] if (typeof metadata_title !== "undefined") { data.push("" + metadata_title + ""); } if (typeof metadata_author !== "undefined") { data.push(""); } if (typeof metadata_date !== "undefined") { data.push(""); } data.push(""); data.push(""); paras.forEach(function (p) {data.push(p);}); // Requires ES5; use a for-loop if you don't have it data.push(""); data.push(""); data = data.join("\n"); alert(data);

提交回复
热议问题