写一个js解析收货地址的方法
时间: 2024-01-28 12:05:38 浏览: 88
好的,下面是一个简单的 JavaScript 函数,可以解析中国大陆的收货地址:
```javascript
function parseAddress(address) {
let province = '';
let city = '';
let district = '';
let street = '';
let postcode = '';
// 匹配省市区信息
const re = /(.*?[省市自治区])(.*?[市区])(.*?[区县]).*/;
const match = re.exec(address);
if (match) {
province = match[1];
city = match[2];
district = match[3];
}
// 匹配街道信息
street = address.replace(province, '').replace(city, '').replace(district, '');
// 匹配邮编信息
const postcodeRe = /(\d{6})/;
const postcodeMatch = postcodeRe.exec(address);
if (postcodeMatch) {
postcode = postcodeMatch[1];
}
return {
province,
city,
district,
street,
postcode
};
}
```
使用方法如下:
```javascript
const address = '广东省深圳市南山区高新科技园北区腾讯大厦';
const parsedAddress = parseAddress(address);
console.log(parsedAddress);
// 输出:{province: "广东省", city: "深圳市", district: "南山区", street: "高新科技园北区腾讯大厦", postcode: ""}
```
需要注意的是,这个函数只是一个简单的示例,对于复杂的地址解析,可能需要使用更加完善的解析库或者服务。
阅读全文