Reputation: 15362
If I have a regex that matches the city/state formats The City, ST
pattern with the consideration that some towns have multiple words in their names, how can I reduce them to this format?
new_town_city_st
My expression: /(\w+(\s))*(\w+)(,\s)(\w{2})/
How can I replace where I have captures (spaces) with underscores when I don't know how many words each town name will be?
Upvotes: 0
Views: 152
Reputation: 50177
Just replace all repeated non-word characters (\W
) with an underscore as follows:
var locationInput = 'New Town City, ST';
var underscoreLocation = function(location) {
return location.replace(/\W+/ig, '_').toLowerCase();
};
var locationOutput = underscoreLocation(locationInput);
// => new_town_city_st
Upvotes: 3
Reputation: 32532
myString=myString.replace(/,\s*|\s+/g,'_');
edited to throw comma into the mix
edit: your post didn't explicitly say it but if you wanted it to be lower cased:
myString=myString.replace(/,\s*|\s+/g,'_').toLowerCase();
Upvotes: 0