aviya.developer
aviya.developer

Reputation: 3613

How to remove the building number and entrance from an address string with regex?

I have various address strings that I would like to automatically clean from the building number part, leaving only the street address.

examples:

"15A W 131st St, New York, NY 10037, USA"
"W 131st St, New York, NY 10037, USA"

"125 E 145th St, New York, NY 10037, USA"
"E 145th St, New York, NY 10037, USA"

"3 Rue Auguste Bartholdi, 75015 Paris, France"
"Rue Auguste Bartholdi, 75015 Paris, France"

I have tried working with String.prototype.match() and the following regex: /[^0-9\s].+/ which works well to remove numbers but doesn't work if the building has an alphabetic entrance (35A, 20B, etc.). Working with the alphabetic character got me in problems about the rest of the string.

Upvotes: 4

Views: 1033

Answers (2)

Code Maniac
Code Maniac

Reputation: 37775

The best solution IMO opinion is using regex

[^\s]+\s+

Reason is better than split splice and join approach is you're having a n overhead first change string to array and than after manipulation again change it back to string, whereas replace just does the manipulation no conversion from string to array and than again back to string

let strs = ["15A W 131st St, New York, NY 10037, USA","125 E 145th St, New York, NY 10037, USA","3 Rue Auguste Bartholdi, 75015 Paris, France"]

strs.forEach(str=>{
  let final = str.replace(/^[^\s]+\s+/,'')
  console.log(final)
})

Upvotes: 1

aviya.developer
aviya.developer

Reputation: 3613

My main problem was that I was trying to match the rest of the string and keep it with String.match() instead of targeting the beginning of the string and deleting it with String.replace().

A few regex expressions that solve when using this String.replace()attitude:

address.replace(/^\d+[A-z]?\s/, '')
address.replace(/^[^\s]+\s/, '')

Another solution would be to target the white spaces by using the String.split() method. This means converting to array of words, deleting the first word, and joining the array into a new clean string.

code:

let newAddress = fullAddress.split(" ").slice(1).join(" ");

Upvotes: 2

Related Questions