例如,我有一个字符串Atlantic-City-NJ
如何使用JavaScript正则表达式(或任何其他方式)将字符串格式化为Atlantic City, NJ
?
我遇到问题,因为可能会有不同的空格:Atlanta, GA
vs Atlantic City, NJ
vs Lake Havasu City, AZ
答案 0 :(得分:1)
你当然可以使用U.S. state codes,但如果验证不重要,你可以像这样完成所有工作:
var str = "Atlantic-City-NJ";
alert(str.replace(/(.+)\-([A-Z]{2})$/, "$1, $2").replace("\-", " "));

答案 1 :(得分:0)
这个表达式将为您提供两个部分:
([\w-]+)([A-Z]{2})
“Atlantic-City-”和“NJ”。
你可以拿这两部分,在第一部分做一个字符串替换,将连字符转换成空格,然后从结果中形成一个字符串,一个逗号,再加上第二部分。
如果您想了解更多细节,请与我们联系。
答案 2 :(得分:0)
您可以这样做:
var test = "Atlantic-City-NJ";
test = test.split("-");
var result = "";
for (var i = 0; i < test.length; i++) {
if (i == test.length - 1)
result += ",";
result += " " + test[i];
}
//result = "Atlantic City, NJ"
alert(result);
答案 3 :(得分:0)
以下表达式将匹配最后一个连字符( - )和国家/地区代码
/([\w-]+)(-(([^-])+)$)/
这样你可以做到
string.replace(/([\w-]+)(-(([^-])+)$)/, '$1, $3').replace(/-/g, ' ')
这将用逗号和国家/地区代码替换最后的连字符和国家/地区代码,并用空格替换其余的连字符。
正则表达式描述:
1st Capturing group ([\w-]+)
[\w-]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\w match any word character [a-zA-Z0-9_]
- the literal character -
2nd Capturing group (-(([^-])+)$)
- matches the character - literally
3rd Capturing group (([^-])+)
4th Capturing group ([^-])+
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
[^-] match a single character not present in the list below
- the literal character -
$ assert position at end of the string
答案 4 :(得分:-1)
var cs = ["Lake-Havasu-City-AZ", "Altanta-GA", "Atlantic-City-NJ", "Atlantic-City"];
for ( var i in cs )
console.log(cs[i].replace( new RegExp('-([A-Z]+)$'), ', $1').replace('-',' ','g'))
// prints...
Lake Havasu City, AZ
Altanta, GA
Atlantic City, NJ
Atlantic City
如果您想更简洁地了解州代码,可以将[A-Z]+
替换为[A-Z]{2}
。