Concatenating strings with `if` statements in JavaScript

后端 未结 5 786
眼角桃花
眼角桃花 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:53

    I'd use a ternary operator:

    data = "\n"
         + "\n" 
         + ( typeof metadata_title  !== "undefined" ?  "" + metadata_title + "\n"                             : "" )
         + ( typeof metadata_author !== "undefined" ?  "\n" : "" )
         + ( typeof metadata_date   !== "undefined" ?  "\n"     : "" )
         + "\n"
         + "\n"
         + "\n"
         + paras.join("\n\n")
         + "\n"
         + "\n"
         + "\n"
         + ""
    ;
    

提交回复
热议问题