我如何缩写街道地址?

时间:2019-04-27 09:28:52

标签: javascript node.js

例如,看看以下内容...

1400 West Mockingbird Lane => 1400 W Mockingbird Ln
1323 East Lake St => 1323 E Lake St
1700 Belmont Avenue => 1700 Belmont Ave
4565 Dunhill Court => 4565 Dunhill Ct
1100 west 7th street => 1100 W 7th St

1 个答案:

答案 0 :(得分:3)

var func = {}
func.toTitleCase = str => {
  if(typeof(str) === 'undefined')
    return
  return str.toLowerCase().replace(/(?:^|\s|\/|\-)\w/g, match => { 
    return match.toUpperCase();  
  })
}

func.formatStreetAddress = address => {
    address = func.toTitleCase(address).trim()
    address = address.replace(/\./g, '').replace(/\,/g, '')
    var replaceWords = {
      'Boulevard': 'Blvd',
      'Circle': 'Circle',
      'Court': 'Ct',
      'Drive': 'Dr',
      'Road': 'Rd',
      'Avenue': 'Ave',
      'Lane': 'Ln',
      'Place': 'Pl',
      'Street': 'St',
      'Way': 'Wy',
      'East': 'E',
      'West': 'W',
      'South': 'S',
      'North': 'N'
    }
    address = address.split(' ')
    var formatted_address = [],
    last_abbr_index = 0
    address.forEach((word, index) => {
      if(replaceWords[word]) {
        formatted_address.push(replaceWords[word])
        if(last_abbr_index == index - 1)
          formatted_address[last_abbr_index] = address[last_abbr_index]
        last_abbr_index = index
        return
      }
      formatted_address.push(word)
    })
    return formatted_address.join(' ')
}
func.formatStreetAddress('1100 west 7th street')