JS寄快递地址智能解析的实现代码
去年做了些前端内容,最近在整理⼀些稍微有点⽤的内容,⽐如智能解析地址,⽤户只要输⼊:张三1351111111江苏省扬州市⼴陵区XX⼩区X楼xxx 室,就能解析出姓名、电话、省市区、地址信息了。是不是很⽅便?
纯JavaScript,⽆需Jquery,轻量级的JS包。可参考以下代码:
let defaultData = [];
const mCity = {};
const mArea = {};
/**
* 处理原始地址数据转换成专⽤数据
* @param list 原始数据
* @param init 是否初始化如传空已转换过不会再次转换
* @returns {boolean}
*/
function parseArea(list, init) {
if (!init && defaultData.length) {
return true;
}
defaultData = list;
defaultData.forEach(province => {
if (province.city) {
province.city.forEach(city => {
if (city.name !== '其他') {
if (!mCity[city.name]) {
mCity[city.name] = [];
}
mCity[city.name].push({
p: province.name,
c: city.name,
a: city.area || []
});
}
if (city.area) {
city.area.forEach(area => {
if (area !== '其他') {
if (!mArea[area]) {
mArea[area] = [];
}
mArea[area].push({
p: province.name,
c: city.name
})
}
})
}
})
}
});
}
/**
* 解析邮编
* @param
* @returns <array>
*/
function zipCodeFormat() {
let list = []
zipCode.forEach((el) => {
if (el.child) {
el.child.forEach((event) => {
if (event.child) {
event.child.forEach(element => {
list.push(element.zipcode)
})
}
})
}
})
return list;
}
//专⽤数据处理
let zipCodeList = zipCodeFormat();//邮编
parseArea(areaList);//地址
/**
* 解析
* @param address 任意地址字符串
* @returns {{name: string, mobile: string, detail: string, zip_code: string, phone: string}}
*/
function parse(address) {
const parse = {
name: '',
mobile: '',
detail: '',
zip_code: '',
phone: ''
};
//去除空格...
address = place(/\r\n/g, ' ').replace(/\n/g, ' ').replace(/\t/g, ' ');
address = place(/\s+/g, "");
//⾃定义去除关键字,可⾃⾏添加
const search = ['地址', '收货地址', '收货⼈', '收件⼈', '收货', '邮编', '电话', ':', ':', ';', ';', ',', ',', '。', ];
search.forEach(str => {
address = place(new RegExp(str, 'g'), ' ')
});
//多个空格replace为⼀个
address = place(/ {2,}/g, ' ');
//整理电话格式
address = place(/(\d{3})-(\d{4})-(\d{4})/g, '$1$2$3');
address = place(/(\d{3}) (\d{4}) (\d{4})/g, '$1$2$3');
const mobileReg = /(86-[1][0-9]{10})|(86[1][0-9]{10})|([1][0-9]{10})/g;
const mobile = (address);
if (mobile) {
address = place(mobile[0], ' ')
}
//电话
const phoneReg = /(([0-9]{3,4}-)[0-9]{7,8})|([0-9]{12})|([0-9]{11})|([0-9]{10})|([0-9]{9})|([0-9]{8})|([0-9]{7})/g;
const phone = (address);
if (phone) {
parse.phone = phone[0];
address = place(phone[0], ' ')
indexof能用于数组吗}
//邮编(加⼊门牌号;考虑到重复邮编问题;去除之前简单的六位数字校验)
for (let index = 0; index < zipCodeList.length; index++) {
if (address.indexOf(zipCodeList[index]) != -1) {
let num = address.indexOf(zipCodeList[index]);
let code = address.slice(num, num + 6);
parse.zip_code = code;
address = place(code, '')
}
}
/* 废弃
const zipReg = /([0-9]{6})/g;
const zip = (address);
if (zip) {
parse.zip_code = zip[0];
address = place(zip[0], '')
}
*/
address = place(/ {2,}/, ' ');
//console.log(address)
let detail = detail_parse_im());
if (!detail.city) {
detail = detail_im());
if (detail.area && !detail.city) {
detail = detail_im(), {
ignoreArea: true
});
console.log('smart_parse->ignoreArea(忽略区)');
} else {
// console.log('smart_parse');
}
//这个待完善
const list = place(detail.province, '').replace(detail.city, '').replace(detail.area, '').split(' ').filter(str => str); //详细住址划分关键字
//注意:只需要填写关键字最后⼀位即可:⽐如单元填写元即可!
const address_detail_list = ['室', '楼', '元', '号', '幢', '门', '户'];
if (list.length > 1) {
list.forEach(str => {
if (!parse.name || str && str.length < parse.name.length) {
parse.name = im()
}
});
if (parse.name) {
detail.addr = place(parse.name, '').trim()
}
} else {//若名字写在详细地址后⾯,根据address_detail_list进⾏分割;
let key = [];
address_detail_list.forEach((el) => {
var max = key.sort(function (a, b) {
return b - a;
})[0];
if (max != -1) {
let addrBuild = detail.addr.slice(0, max + 1);
let addrNum = place(addrBuild, '').replace(/[^0-9]+/g, '');
let userName = place(addrBuild + addrNum, '')
detail.addr = addrBuild + addrNum
parse.name = userName
}
}
} else {
if (detail.name) {
parse.name = detail.name
} else {
const list = detail.addr.split(' ').filter(str => str);
if (list.length > 1) {
parse.name = list[list.length - 1]
}
if (parse.name) {
detail.addr = place(parse.name, '').trim()
}
}
}
parse.province = detail.province;
parse.city = detail.city;
parse.area = detail.area;
parse.addr = detail.addr;
return parse;
}
/
**
* 正向解析模式
* 从前到后按 province city addr 逐级筛选
* 有city的值即可说明解析成功
* 此模式对地址顺序有要求
* @param address
* @returns {{province: string, city: string, area: string, addr: string}}
*/
function detail_parse_forward(address) {
const parse = {
province: '',
city: '',
area: '',
addr: '',
name: '',
};
const provinceKey = ['特别⾏政区', '古⾃治区', '维吾尔⾃治区', '壮族⾃治区', '回族⾃治区', '⾃治区', '省省直辖', '省', '市']; const cityKey = ['布依族苗族⾃治州', '苗族侗族⾃治州', '⾃治州', '州', '市', '县'];
for (let i in defaultData) {
const province = defaultData[i];
let index = address.indexOf(province.name);
if (index > -1) {
if (index > 0) {
//省份不是在第⼀位,在省份之前的字段识别为名称
parse.name = address.substr(0, index).trim();
}
parse.province = province.name;
address = address.substr(index + province.name.length);
for (let k in provinceKey) {
if (address.indexOf(provinceKey[k]) === 0) {
address = address.substr(provinceKey[k].length);
}
}
for (let j in province.city) {
const city = province.city[j];
index = address.indexOf(city.name);
if (index > -1 && index < 3) {
parse.city = city.name;
address = address.substr(index + parse.city.length);
for (let k in cityKey) {
if (address.indexOf(cityKey[k]) === 0) {
address = address.substr(cityKey[k].length);
}
}
if (city.area) {
for (let k in city.area) {
const area = city.area[k];
index = address.indexOf(area);
if (index > -1 && index < 3) {
parse.area = area;
address = address.substr(index + parse.area.length);
break;
}
}
}
}
parse.addr = im();
break;
}
}
return parse;
}
/**
* 逆向解析从后【县,区,旗】往前解析
* 有地区就能⼤概返回地址了
* @param address
* @param ignoreArea 是否忽视区因为地址中含有区容易导致匹配错误例:⼭东省蓬莱市黄海花园东区
西门宝威学堂曲荣声收157******** * @returns {{province: string, city: string, area: string, name: string, _area: string, addr: string}}
*/
function detail_parse(address, {
ignoreArea = false
} = {}) {
const parse = {
province: '',
city: '',
area: '',
name: '',
_area: '',
addr: '',
};
let areaIndex = -1,
cityIndex = -1;
address = place(' ', ' ');
if (!ignoreArea && address.indexOf('县') > -1 || !ignoreArea && address.indexOf('区') > -1 || !ignoreArea && address.indexOf('旗') > -1) {
if (address.indexOf('旗') > -1) {
areaIndex = address.indexOf('旗');
parse.area = address.substr(areaIndex - 1, 2);
}
if (address.indexOf('区') > -1) {
areaIndex = address.indexOf('区');
if (address.lastIndexOf('市', areaIndex) > -1) {
cityIndex = address.lastIndexOf('市', areaIndex);
parse.area = address.substr(cityIndex + 1, areaIndex - cityIndex);
} else {
parse.area = address.substr(areaIndex - 2, 3);
}
}
if (address.indexOf('县') > -1) {
areaIndex = address.lastIndexOf('县');
if (address.lastIndexOf('市', areaIndex) > -1) {
cityIndex = address.lastIndexOf('市', areaIndex);
parse.area = address.substr(cityIndex + 1, areaIndex - cityIndex);
} else {
parse.area = address.substr(areaIndex - 2, 3);
}
}
parse.addr = address.substr(areaIndex + 1);
} else {
if (address.indexOf('市') > -1) {
areaIndex = address.indexOf('市');
parse.area = address.substr(areaIndex - 2, 3);
parse.addr = address.substr(areaIndex + 1);
} else {
parse.addr = address
}
}
if (address.indexOf('市') > -1 || address.indexOf('盟') > -1 || address.indexOf('州') > -1) {
if (address.indexOf('市') > -1) {
parse._area = address.substr(address.indexOf('市') - 2, 2);
}
if (address.indexOf('盟') > -1 && !mCity[parse._area]) {
parse._area = address.substr(address.indexOf('盟') - 2, 2);
}
if (address.indexOf('州') > -1 && !mCity[parse._area]) {
parse._area = address.substr(address.indexOf('州') - 2, 2);
}
}
parse.area = im();
if (parse.area && mArea[parse.area]) {
if (mArea[parse.area].length === 1) {
parse.province = mArea[parse.area][0].p;
parse.city = mArea[parse.area][0].c
} else {
parse._area = parse._im();
const addr = address.substr(0, areaIndex);
const d = mArea[parse.area].find(item => {
return item.p.indexOf(addr) > -1 || item.c === parse._area;
if (d) {
parse.province = d.p;
parse.city = d.c
} else {
}
}
} else {
if (parse._area) {
const city = mCity[parse._area];
if (city) {
parse.province = city[0].p;
parse.city = city[0].c;
parse.addr = address.substr(address.indexOf(parse.city) + parse.city.length + 1);
parse.area = '';
for (let i in city[0].a) {
if (parse.addr.indexOf(city[0].a[i]) === 0) {
parse.area = city[0].a[i];
parse.addr = place(city[0].a[i], '');
break;
}
}
}
} else {
parse.area = '';
}
}
parse.addr = im();
return parse
}
/*export {parseArea}
export default parse;*/
下⾯介绍部分使⽤实例:
Html
<textarea class="weui-textarea sj_textarea" onchange="smart_parse2()" placeholder="[智能填写] 例如:张三1351111111江苏省扬州市⼴陵区XX⼩区X楼xxx室" rows="2"></textarea> JavaScript
//智能识别地址
function smart_parse2() {
var value = $('.sj_textarea').val();
console.log(parse(value));//这⾥可以看⼀下解析出来的内容
var html = '';
for (var key in parse(value)) {
if (parse(value)[key]) {
html += `<p>` + key + `:` + parse(value)[key] + `</p>`
}
} //把解析的内容在赋值到页⾯元素中(这⼉业务使⽤的Jq,实际上不需要)
$('#sj_name').val(parse(value).name);
$('#sj_phone').val(parse(value).phone);
$('#city-picker2').val(parse(value).province + ' ' + parse(value).city + ' ' + parse(value).area);
$('#sj_addr').val(parse(value).addr);
}
使⽤起来⾮常⽅便,容错率也⾼。
到此这篇关于JS寄快递地址智能解析的⽂章就介绍到这了,更多相关js 寄快递内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论