js截取地址详细信息(除去省市区、市市区、自治区市区)

发布于:2025-06-26 ⋅ 阅读:(21) ⋅ 点赞:(0)
  • 解析地址字符串,严格匹配【省市区】、【市市区】、【自治区市区】格式
  • 格式要求:
    1. 省市区:XX省XX市XX区/县
    1. 市市区:XX市XX市XX区/县 (仅限直辖市)
    1. 自治区市区:XX自治区XX市XX区/县
  • 符合上述格式则返回剩余部分(乡镇/街道及以下),否则返回原地址
function parseAddress(address) {
  // 直辖市列表
  const municipalities = ['北京市', '天津市', '上海市', '重庆市'];
  
  // 严格匹配三种标准格式
  const strictRegex = /^(
    (?<province>[^]+)(?<city>[^]+)(?<county>[^市县区旗]+(?:||))|  // 省市区格式
    (?<municipality>北京市|天津市|上海市|重庆市)(?<district>[^]+)(?<county2>[^市县区旗]+(?:||))|  // 市市区格式(仅限直辖市)
    (?<province2>.+自治区)(?<city2>[^]+)(?<county3>[^市县区旗]+(?:||)) // 自治区市区格式
  )(?<rest>.*)$/;

// 检查地址中是否包含多个"省"或"自治区",如果是则直接返回原地址
  const provinceCount = (address.match(//g) || []).length;
  const autonomousRegionCount = (address.match(/自治区/g) || []).length;
  
  if (provinceCount > 1 || autonomousRegionCount > 1 || (provinceCount > 0 && autonomousRegionCount > 0)) {
    return address;
  }
  
  // 去除分隔符并合并连续空格
  const normalizedAddr = address.replace(/[^\u4e00-\u9fa50-9a-zA-Z]/g, '');
  const match = strictRegex.exec(normalizedAddr);
  
  if (match?.groups) {
    // 检查匹配的是哪种格式
    const isProvinceFormat = match.groups.province && match.groups.city && match.groups.county;
    const isMunicipalityFormat = match.groups.municipality && match.groups.district && match.groups.county2;
    const isAutonomousFormat = match.groups.province2 && match.groups.city2 && match.groups.county3;
    
    // 仅当完全匹配标准格式时才处理
    if (isProvinceFormat || isMunicipalityFormat || isAutonomousFormat) {
      // 对于市市区格式,确保第一个市是直辖市
      if (isMunicipalityFormat && !municipalities.includes(match.groups.municipality)) {
        return address;
      }
      return match.groups.rest || '';
    }
  }
  
  return address;
}

网站公告

今日签到

点亮在社区的每一天
去签到