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 want to insert a break tag.
For eg if #ADDRESS2#
is found in the template, I am using the following code to replace all its occurrences with value in string val.address2
.
template_html = template_html.replace(/#ADDRESS2#/g, '<br />'+ val.address_2);
However there are scenarios when the string val.address2
is empty. In that case, I do not want to insert the break tag.
So I changed my code as follows
if( val.address_2.length > 0 ) {
template_html = template_html.replace(/#ADDRESS2#/g, '<br />'+ val.address_2);
} else {
template_html = template_html.replace(/#ADDRESS2#/g, '');
}
Is there a better way to write the above code as I have multiple Placeholders and for each Placeholder I have to write the code 2 times.
You could take the value with a check.
For more than one placeholder, you could take a dynamic approach and use same pattern for the search and replacements.
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.
The simplest change is to use the ternary operator like this:
Still not particularly elegant but a bit shorter than the original.
You mean, something like this:
You should use the
val.hasOwnProperty
just in case thatval.['address_' + number]
contains a value like0
,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:
All of this checking ensures that it is a non-empty string (or
String
instance, becausenew String()
returns a string object).Checking if it is an instance of
String
prevents issues due totypeof new String()
returningobject
.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.If the same logic should be applied for multiple address fields, then you might benefit from a helper function:
Perhaps you meant this?
You can use ternary operator (empty string evaluates to false)