两种方法:分割地址省市区(含自治区,直辖市,县,自治县)

方法一:

通过js进行处理

 

var str = "湖北省武汉市江夏区文化大道110号";
console.log(that.getArea(str));

//省市区截取
getArea: function(str) {
  let area = {}
  let index11 = 0
  let index1 = str.indexOf("省")
  if (index1 == -1) {
    index11 = str.indexOf("自治区")
    if (index11 != -1) {
      area.Province = str.substring(0, index11 + 3)
    } else {
      area.Province = str.substring(0, 0)
    }
  } else {
    area.Province = str.substring(0, index1 + 1)
  }

  let index2 = str.indexOf("市")
  if (index11 == -1) {
    area.City = str.substring(index11 + 1, index2 + 1)
  } else {
    if (index11 == 0) {
      area.City = str.substring(index1 + 1, index2 + 1)
    } else {
      area.City = str.substring(index11 + 3, index2 + 1)
    }
  }

  let index3 = str.lastIndexOf("区")
  if (index3 == -1) {
    index3 = str.indexOf("县")
    area.Country = str.substring(index2 + 1, index3 + 1)
  } else {
    area.Country = str.substring(index2 + 1, index3 + 1)
  }
  return area;
}

效果如下:

 方法二:

通过正则进行判断

 var str = "湖北省武汉市江夏区文化大道110号";
 var reg = /.+?(省|市|自治区|自治州|县|区)/g; // 省市区的正则
 console.log(str.match(reg));

效果如下:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,根据您的问题,我可以给您提供以下代码: ``` String address = "北京朝阳望京东路2号院"; String province = ""; String city = ""; String county = ""; // 级信息 int provinceIndex = address.indexOf(""); if (provinceIndex != -1) { province = address.substring(0, provinceIndex + 1); } else { provinceIndex = address.indexOf("自治区"); if (provinceIndex != -1) { province = address.substring(0, provinceIndex + 3); } else { provinceIndex = address.indexOf("特别行政"); if (provinceIndex != -1) { province = address.substring(0, provinceIndex + 5); } } } // 级信息 int cityIndex = address.indexOf(""); if (cityIndex != -1) { int preCityIndex = provinceIndex == -1 ? 0 : provinceIndex + 1; city = address.substring(preCityIndex, cityIndex + 1); } else { cityIndex = address.indexOf("自治州"); if (cityIndex != -1) { int preCityIndex = provinceIndex == -1 ? 0 : provinceIndex + 1; city = address.substring(preCityIndex, cityIndex + 3); } } // /级信息 int countyIndex = address.lastIndexOf(""); if (countyIndex == -1) { countyIndex = address.lastIndexOf(""); } if (countyIndex != -1) { int preCountyIndex = cityIndex == -1 ? provinceIndex + 1 : cityIndex + 1; county = address.substring(preCountyIndex, countyIndex + 1); } System.out.println("级信息:" + province); System.out.println("级信息:" + city); System.out.println("/级信息:" + county); ``` 希望这个代码能够对您有所帮助。如果您还有其他问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值