在javascript中使用逗号进行字符串格式化

时间:2012-10-25 14:30:53

标签: javascript string formatting

我的用户地址部分应该用单个字符串格式化 地址组件是

Street  
City  
Phone  
State  
Zip  

并且应格式化为字符串street city, phone, state zip。 (2个逗号)。
问题是每个字段都可以null。因此,如果street == nullcity == null,那么我应该有字符串phone, state zip(1个逗号)。问题在于控制空格数和逗号数 如何避免和减少空检查的次数?
我目前的代码是

  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
  }

4 个答案:

答案 0 :(得分:4)

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(", ");

或者,在没有filtermap的循环中,但将属性名称映射到它们的值:

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(", ");

答案 1 :(得分:1)

将其添加到数组中并删除一些相邻的逗号和空格。

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

答案 2 :(得分:0)

功能更清晰:

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
  }

答案 3 :(得分:0)

将您的字符串放在一个数组中,然后使用join方法并删除多个连续的逗号,只需一个

a = [address.Street, 
     address.City, 
     address.Phone, 
     address.State, 
     address.Zip].join (', ').replace (/(, ){2,}/g, ', ');