November 7, 2019
Issues we've come across, and how we fixed them.
What's The Ucwords() Equivalent In Javascript? Capitalize Each Word In A String

We are wondering why Javascript doesn't have more functions like PHP has. We use the ucwords(); function with PHP when we have to, it capitalizes each word of the string. There is no real equivalent to that in Javascript though, so we have to do a workaround. We suppose there's a lot of ways to do this, but here's the one we settled on because it works and it's concise.

  • <script>
  • var string = 'some example string';
  • var formattedString = string.replace(/\b[a-z]/g,function(l){
  • return l.toUpperCase();
  • });
  • alert(formattedString); //-> will output an alert saying "Some Example String"
  • </script>

Keep in mind, this code will only work within lower case letters from "a" to "z". This is what we were looking for anyways, but just thought we'd throw that out there. That's what the little regex is looking for.

 Profile Picture
Comment

Proudly Serves

Allentown, Bethlehem, Lehigh Valley... and everywhere else!

Follow Our Socials