Reputation: 29693
Let's I have parts of user's address that should be formatted in single string.
Address components are
Street
City
Phone
State
Zip
and should be formatted to string street city, phone, state zip
. (2 commas).
Problem is that every field can be null
. So if street == null
and city == null
, then I should have string phone, state zip
(1 comma). Problem is in controlling number of spaces and number of commas
How can I avoid and minimize the number of null-inspections?
My current code is
var formatAddress = function(address) {
var retVal = ""
if (address.street || address.city)
{
retVal += address.street ? address.street + " " : ""
retVal += address.city ? address.city : ""
retVal += ", ";
}
retVal += address.phone ? address.phone + ", " : ""
retVal += address.state ? address.state : ""
retVal += address.zip ? " " + address.zip : ""
return retVal
}
Upvotes: 1
Views: 1678
Reputation: 16033
Put your strings in an array, then use the join method and remove multipel consecutive commas with a single one
a = [address.Street,
address.City,
address.Phone,
address.State,
address.Zip].join (', ').replace (/(, ){2,}/g, ', ');
Upvotes: 0
Reputation: 664548
var fields = [[address.street, address.city], [address.phone], [address.state, address.zip]];
return fields.map(function(part) {
return part.filter(Boolean).join(" ");
}).filter(function(str) { return str.length; }).join(", ");
Or, in a loop and without filter
and map
, but mapping property names to their values:
var fields = [["street", "city"], ["phone"], ["state", "zip"]];
for (var strs=[], i=0; i<fields.length; i++) {
for (var parts=[], j=0; j<fields[i].length; j++)
if (address[fields[i][j]])
parts.push(address[fields[i][j]]);
if (parts.length)
strs.push(parts.join(" "));
}
return strs.join(", ");
Upvotes: 5
Reputation: 5128
add it to an array and remove some adjacent comma's and spaces.
var street = "street";
var city = "city";
var phone = "phone";
var state = "state";
var zip = "zip";
[
street,
city, ",",
phone, ",",
state,
zip
].join(" ") //add all items with spaces in between
.replace(/(\s*,\s*)+/g, ", ") //remove multiple spaces before or after commas
.replace(/\s+/g, " "); //remove any other double spaces
Upvotes: 1
Reputation: 13655
Could be cleaner with a function:
function formatAddressPart(part,concatString){
return part ? part+concatString : "";
}
var formatAddress = function(address) {
var retVal = ""
if (address.street || address.city)
{
retVal += formatAddressPart(address.street, " ");
retVal += formatAddressPart(address.city,"");
retVal += ", ";
}
retVal += formatAddressPart(address.phone,", ");
retVal += formatAddressPart(address.state," ");
retVal += formatAddressPart(address.zip,"");
return retVal
}
Upvotes: 0