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
You could take the value with a check.
template_html = template_html.replace(
/#ADDRESS2#/g,
val.address_2 && '
' + val.address_2
);
For more than one placeholder, you could take a dynamic approach and use same pattern for the search and replacements.
var val = { address_2: 'foo', country_1: 'bar' }
template_html = 'Address: #ADDRESS2#\nCountry: #COUNTRY1#\nnothing: #NOTHING#'
template_html = template_html.replace(
/#([^#]+)#/g,
(_, group) => {
var key = group.match(/^(\D+)(\d*)$/).slice(1).map(s => s.toLowerCase()).join('_');
return (val[key] || '') && '
' + val[key];
}
);
console.log(template_html);
For getting a smarter replacement, yoou could take the idea of same strings as tempate and for getting the data from an object. In this case, take the replacement value and take this as key for the object or take an empty string for unknown values.
var val = { ADDRESS2: 'foo', COUNTRY1: 'bar' }
template_html = 'Address: #ADDRESS2#\nCountry: #COUNTRY1#\nnothing: #NOTHING#'
template_html = template_html.replace(
/#([^#]+)#/g,
(_, key) => (val[key] || '') && '
' + val[key]
);
console.log(template_html);