我在数组中有[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的唯一答案吗?
答案 0 :(得分:2)
将State
和Zip
连接到数组的同一元素,然后用逗号连接数组:
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);