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

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.



Solution 1:[1]

You can simply uppercase the letters that aren't proceeded by a word character.
This can be checked with a word-boundary \b

let address = "1 pleasant valley drive";

address = address.replace(/\b(\w)/g, (m,g) => g.toUpperCase())

console.log(address);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LukStorms