如何使用正则表达式将街道地址大写?
在我的应用程序中,您可以提交街道地址,在前端我将其全部转换为小写以存储在数据库中。现在,当我获取数据时,我得到一个如下所示的地址: “1令人愉快的山谷驱动器”
我可以制作一个正则表达式来将字符串中每个单词的第一个字母大写吗?
最终目标: “1 Pleasant Valley Dr”
我目前正在使用
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);
:但我需要它来扩展。假设街道地址是:
1234 Rocky Mountain Road
然后我的代码有问题,因为它不会将最后一个单词大写。
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"
Can I make a regex to capitalize the first letter of each word in the string?
End goal:
"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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地将不以单词字符开头的字母大写。
这可以使用字边界
\b
进行检查You can simply uppercase the letters that aren't proceeded by a word character.
This can be checked with a word-boundary
\b