简体   繁体   English

如何使用正则表达式将街道地址大写?

[英]How to use Regex to capitalize a street address?

In my application, you can submit a street address, and in the front end I convert it all to lowercase to be stored in the database.在我的应用程序中,您可以提交一个街道地址,在前端我将其全部转换为小写以存储在数据库中。 Now when I fetch the data I get an address that looks like: "1 pleasant valley drive"现在,当我获取数据时,我得到一个看起来像这样的地址:“1 pleasant valley drive”

Can I make a regex to capitalize the first letter of each word in the string?我可以制作一个正则表达式来将字符串中每个单词的首字母大写吗?

End goal: "1 Pleasant Valley Dr"最终目标:“1 Pleasant Valley Dr”

I'm currently using:我目前正在使用:

let addrFormat =
    address?.split(" ")[0] +" " +
    address?.split(" ")[1].charAt(0).toUpperCase() +
    address?.split(" ")[1].substring(1) +
    " " + address?.split(" ")[2].charAt(0).toUpperCase() +
    address?.split(" ")[2].substring(1);

but I need it to scale.但我需要它来扩展。 lets say the street address is:假设街道地址是:

1234 Rocky Mountain Road

Then I have a problem with my code because it wont capitalize the last word.然后我的代码有问题,因为它不会把最后一个字大写。

You can simply uppercase the letters that aren't proceeded by a word character.您可以简单地将没有单词字符的字母大写。
This can be checked with a word-boundary \b这可以用字边界\b检查

 let address = "1 pleasant valley drive"; address = address.replace(/\b(\w)/g, (m,g) => g.toUpperCase()) console.log(address);

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

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