November 7, 2019
Advice I Wish I Could Take For Myself
What's The Ucwords() Equivalent In Javascript? Capitalize Each Word In A String

I am wondering why Javascript doesn't have more functions like PHP has. I use the ucwords(); function with PHP when I 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. I suppose there's a lot of ways to do this, but here's the one I settled on because it works and it's small.

  • <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 I'd throw that out there. That's what the little regex is looking for.

 Profile Picture