Concatenating strings with `if` statements in JavaScript

后端 未结 5 788
眼角桃花
眼角桃花 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 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 = "\
                \
                    #title#\
                    \
                    \
                \
                \
                \
                ";
    
    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 : "");
    

提交回复
热议问题