【问题标题】:Javascript capitalizing string after 2 characters2个字符后的Javascript大写字符串
【发布时间】:2022-11-05 07:04:22
【问题描述】:

我有一个如下所示的地址: 琼斯大道 3513 号公寓 #500a

如何将 Ap 之后的任何字符大写为全部大写。包括公寓号码后的a。

3513 琼斯大道 APT #500A

我开始使用 indexOf!任何帮助表示赞赏。

NewAddress = toggleCaseText(GetRecordsLF_Address); //3513 Jones Drive Apt #500a
FinalAddress = NewAddress.substring(NewAddress.indexOf('Ap') + 1); //needs to be 3513 Jones Drive APT #500A

【问题讨论】:

  • 43 Apple Blossom Rd.呢?
  • 那么“3513 Jones Drive Suite 500a”呢?或者如果用户打开他们的大写锁定并提交“3513 jONES DRIVE aPT 500a”怎么办?
  • 有一些服务可以帮助规范化地址

标签: javascript string formatting


【解决方案1】:

使用带有将匹配转换为大写的回调函数的正则表达式替换。

let NewAddress = '3513 Jones Drive Apt #500a';
let FinalAddress = NewAddress.replace(/Ap.*/, match => match.toUpperCase());
console.log(FinalAddress);

【讨论】:

  • 执行此操作时出现语法错误 FinalAddress = NewAddress.replace(/Ap.*/, match => match.toUpperCase());
  • 您使用的是没有箭头功能的旧版本 node.js 吗?
  • 是的,一个非常旧的版本我不能使用 console.log() 在这个正在开发的系统中回调
  • 然后只需将箭头函数替换为传统函数即可。function(match) { return match.toUpperCase(); }
  • 这有误报,例如10 Apple Tree Ct.
【解决方案2】:

您可以使用正则表达式替换:

[
  '3513 Jones Drive APT #500A',
  '351 Jones Drive Apt #500a',
  '35 Jones Drive AP #500B',
  '3 Jones Drive Ap #500b',
  '3513 Jones Drive App #500A', // no match
  '43 Apple Blossom Rd.' // no match
].forEach(function(str) {
  var fixed = str.replace(/APT?.*/i, function(m) {
    return m.toUpperCase();
  });
  console.log(str + ' => ' + fixed);
});

输出:

3513 Jones Drive APT #500A => 3513 Jones Drive APT #500A
351 Jones Drive Apt #500a => 351 Jones Drive APT #500A
35 Jones Drive AP #500B => 35 Jones Drive AP #500B
3 Jones Drive Ap #500b => 3 Jones Drive AP #500B
3513 Jones Drive App #500A => 3513 Jones Drive App #500A
43 Apple Blossom Rd. => 43 Apple Blossom Rd.

正则表达式的解释:

  • -- 字边界
  • AP -- 期望文字 AP
  • T? -- 可选 T
  • -- 字边界
  • .* -- 将所有内容捕获到字符串末尾
  • /i -- 忽略大小写

您可能希望使正则表达式更加严格以避免误报,例如/APT? +#?w+/i

更新:更改了旧 JavaScript 语法的代码。

【讨论】:

    【解决方案3】:

    let NewAddress = '3513 Jones Drive Apt #500a';
    let FinalAddress = NewAddress.replace(/Ap.*/, match => match.toUpperCase());
    console.log(FinalAddress);

    【讨论】:

    • 这与我半小时前发布的答案完全相同。
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2011-05-15
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多