如何在城市和州代码之间用逗号将城市和州从短划线格式化为空格.(javascript)

How to format city and state from dashes to spaces with a comma between city and state code. (javascript)

本文关键字:城市 格式化 空格 javascript 代码 之间      更新时间:2023-09-26

例如,我有一个字符串Atlantic-City-NJ如何使用JavaScript正则表达式(或任何其他方式)将字符串格式化为Atlantic City, NJ

我遇到了问题,因为可能有不同数量的空间:Atlanta, GAAtlantic City, NJLake Havasu City, AZ

你当然可以使用美国的州代码,但如果验证不重要,你可以这样做:

var str = "Atlantic-City-NJ";
alert(str.replace(/(.+)'-([A-Z]{2})$/, "$1, $2").replace("'-", " "));

以下表达式将匹配最后一个连字符(-)和国家/地区代码

/(['w-]+)(-(([^-])+)$)/

有了这个,你可以做

string.replace(/(['w-]+)(-(([^-])+)$)/, '$1, $3').replace(/-/g, ' ')

这将用逗号和国家代码替换最后一个连字符和国家代码,并用空格替换其余连字符。

Regex描述:

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

您可以这样做:

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);

这个表达式将为您提供两个部分:

(['w-]+)([A-Z]{2})

"大西洋城"answers"新泽西"。

你可以用这两个部分,在第一个部分上做一个字符串替换,将连字符变成空格,然后用结果、逗号和第二个部分组成一个字符串。

如果你想了解更多细节,请告诉我。

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]{2}替换[A-Z]+