Javascript Replace - Dynamic Value of Replacement

后端 未结 7 1686
半阙折子戏
半阙折子戏 2020-12-21 10:58

I have a template in a String and I want to replace a few of the placeholders with the values that I have in another string. For every placeholder that I replace, I also wan

7条回答
  •  被撕碎了的回忆
    2020-12-21 11:06

    If the same logic should be applied for multiple address fields, then you might benefit from a helper function:

    template_html = template_html
        .replace(/#CITY1#/g, PrefixBrIfNotEmpty(val.city_1))
        .replace(/#CITY2#/g, PrefixBrIfNotEmpty(val.city_2))
        .replace(/#CITY3#/g, PrefixBrIfNotEmpty(val.city_3))
        .replace(/#ADDRESS1#/g, PrefixBrIfNotEmpty(val.address_1))
        .replace(/#ADDRESS2#/g, PrefixBrIfNotEmpty(val.address_2))
        .replace(/#ADDRESS3#/g, PrefixBrIfNotEmpty(val.address_3));
    
    function PrefixBrIfNotEmpty(str) {
        return str ? '
    ' + str : ''; }

提交回复
热议问题