添加逗号作为分隔符,但不在州和邮政编码之间添加

时间:2016-06-06 09:11:45

标签: javascript jquery

我在数组中有[Address][City][State][Zip],但其中任何一个或多个都可能为空。

我想在每个键值对之间用逗号显示它们,但如果状态和ZIP都存在,则它们之间不应该有逗号!

这是我到目前为止所做的:

    var student_address_array = [Address, City, State, Zip]; //Put variables into array
    var student_address_array_cleaned = student_address_array.filter(function(v){return v!==''}); //Remove empty array items
    var student_address = student_address_array_cleaned.join(', '); // Convert array to string with ', ' as the delimiter

但这会在邮政编码之前加上逗号......

是某种RegEx的唯一答案吗?

1 个答案:

答案 0 :(得分:2)

StateZip连接到数组的同一元素,然后用逗号连接数组:

var student_address_array = [student_info.Address1, student_info.City, (student_info.State + ' ' + student_info.Zip).trim()];
var student_address = student_address_array.join(', ');



var student_info = {
  Address1: 'address1',
  City: 'city',
  State: 'CA',
  Zip: '90210'
};

var student_address_array = [student_info.Address1, student_info.City, (student_info.State + ' ' + student_info.Zip).trim()];
var student_address = student_address_array.join(', ');

console.log(student_address);