繁体   English   中英

如何在城市和州代码之间用逗号分隔从虚线到空格的城市和州格式。 (javascript)

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

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

我遇到问题是因为可能会有不同的空间: Atlanta, GA vs Atlantic City, NJ vs Lake Havasu City, AZ

您当然可以使用美国州代码 ,但是如果验证不重要,则可以按以下方式完成所有工作:

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

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

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

“大西洋城”和“新泽西州”。

您可以使用这两部分,在第一个部分上进行字符串替换以将连字符转换为空格,然后从结果中形成一个字符串,用逗号加上第二个部分。

让我知道您是否需要更多细节。

您可以执行以下操作:

 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-]+)(-(([^-])+)$)/

有了这个你可以做

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

如果您想更简洁地表示状态代码,可以将[AZ]+替换为[AZ]{2}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM