如果我有一个与城市/州格式 The City, ST
模式匹配的正则表达式,并考虑到某些城镇的名称中包含多个单词,我如何将它们简化为这种格式?
new_town_city_st
我的表达式:/(\w+(\s))*(\w+)(,\s)(\w{2})/
当我不知道每个城镇名称有多少个单词时,如何用下划线替换捕获(空格)的位置?
最佳答案
只需将所有重复的非单词字符 (\W
) 替换为下划线,如下所示:
var locationInput = 'New Town City, ST';
var underscoreLocation = function(location) {
return location.replace(/\W+/ig, '_').toLowerCase();
};
var locationOutput = underscoreLocation(locationInput);
// => new_town_city_st
关于javascript - 用正则表达式替换捕获的空格未知次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18992987/