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 mean, something like this:
template_html = template_html.replace(/#ADDRESS(\d+)#/g, function(address, number) {
return val.hasOwnProperty('address_' + number)
? '<br />' + val['address_' + number]
: '';
};
You should use the val.hasOwnProperty
just in case that val.['address_' + number]
contains a value like 0
, false
, ''
, undefined
, NaN
or other falsy values.
It makes sure the value is displayed anyway, because an undefined
isn't the same as not having the property at all.
It also avoids to get a value from the prototype, just in case.
This is based on mplungjan's answer.
If this is undesirable, and you only want to show strings, try this:
template_html = template_html.replace(/#ADDRESS(\d+)#/g, function(address, number) {
return val.hasOwnProperty('address_' + number)
&& val['address_' + number].length
&& (
(typeof val['address_' + number]) === 'string'
|| val['address_' + number] instanceof String
)
? '<br />' + val['address_' + number]
: '';
};
All of this checking ensures that it is a non-empty string (or String
instance, because new String()
returns a string object).
Checking if it is an instance of String
prevents issues due to typeof new String()
returning object
.
Arrays and array-like objects have a length
attributes (e.g.: jQuery instance, NodeList, {length: 1}
, [0]
and similars), but you dont want to show them as strings.