Reputation: 13771
How to identify and remove a zip code from a string that contains city, state, zip?
I will always have a city, state, zip in the following structure:
"San Diego, CA 92115"
I need to remove the zip code and only return
"San Diego, CA"
Upvotes: 1
Views: 1877
Reputation: 4610
var str = "San Diego, CA 92115";
str = str.replace(/ \d{5}$/, '');
\d{5}
- means 5 digits, you can change this count of digits or just use \d+
- any number of digits.
$
- means you will remove digits only at the end of string.
Upvotes: 0
Reputation: 875
When the provided string contains five digits at the end, optionally followed by spaces, this code will remove the digits and any spaces that may follow. If five digits are not detected, the original string will be used.
var s="San Diego, CA 92115";
var matches=s.match(/(.*)\d{5}\s*$/);
alert(matches?matches[1]:s);
Upvotes: 0
Reputation: 175976
As its a fixed format just remove all following & including the last space:
str = str.substr(0, str.lastIndexOf(" "));
Or if all Zips are 5 digits:
str = str.slice(0, -6);
Upvotes: 2
Reputation: 10458
you can remove the digits using
let str = "San Diego, CA 92115";
// if the pincode is the only digit
console.log(str.replace(/\d+/, ''));
// if the pincode is only 5 digit always
console.log(str.replace(/\d{5}/, ''));
Upvotes: 2