Tutorial

Capitalizing Strings in JavaScript

Published on November 28, 2019
author

joshtronic

Capitalizing Strings in JavaScript

This tutorial is out of date and no longer maintained.

I love JavaScript, but it’s lack of built-in string manipulation in comparison to PHP is lacking. Sure, you could pull in a third-party dependency for your string manipulation needs, but oftentimes that carries way more weight than you probably want in your application.

Even though JavaScript lacks the baked-in goodies, it still comes with more than enough functionality to make it easy to handle capitalization tasks.

Getting started

Since we’re going to be using pure JavaScript, there’s nothing additional that will need to be installed. In fact, you can easily follow along in your browser’s console, or via the Node.js REPL!

How to capitalize an entire string

This one’s easy and probably already something you already know about. To capitalize an entire string, simply call .toUpperCase() on the string:

let myString = 'alligator';
myString.toUpperCase();

Which will convert the lower case string to the upper case, ALLIGATOR.

This can even work on mixed case strings as well:

myString = 'AlliGator';
myString.toUpperCase();

Same result, the string becomes ALLIGATOR.

How to capitalize the first letter of a string

Okay, so that first one was easy and things are about to get significantly more complex really quickly.

Because there isn’t a built in method on the String prototype to upper case just the first letter of the string, we have to get a bit creative.

The gist of things is that we are going to need to grab the very first letter of the string, capitalize it, then grab the rest of the string, and re-assemble things.

Fortunately, we don’t have to walk through each of those steps and can just use a regular expression to grab the first letter and capitalize it, returning the modified string:

myString = 'the quick green alligator...';
myString.replace(/^\w/, (c) => c.toUpperCase());

This will result in the string becoming The quick green alligator....

This is great as long as your string doesn’t have any spaces padding the front of it.

If you aren’t sure if you are going to encounter said padding, like when you’re dealing with the inconsistencies of user-generated content, you can include the .trim() method to clean things up before capitalizing:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

How to capitalize the first letter of each word in a string

Similar to capitalizing the first letter of a string, there’s nothing baked into JavaScript to capitalize the first letter of each word in a string, also called title casing.

We also need to take a similar approach, the string needs to be broken into words, each word needs to be capitalized and then reassembled with spaces in between them.

We could approach this by using .split() and .join() with our capitalization regular expression from earlier sandwiched in between.

Or, we could approach it by simply adding another regular expression to the mix:

myString = 'the quick green alligator...';
myString.replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

Will give us The Quick Green Alligator....

Because we’re isolating the words themselves, this method is a bit more fault tolerant when it comes to proceeding spacing. You may still want to trim() the string though, if you don’t want said padding in the resulting string.

If you’re working with a string that has words that are MiXeD CaSe, you may also want to include a call to .toLowerCase() to make things consistent.

myString = '  tHE QuICk GrEEn alliGATOR...  ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

Still gets us The Quick Green Alligator....

Granted, this will also lower case any acronyms in the string, so your mileage may vary!

Conclusion

Even without additional utility methods, JavaScript’s existing toolbox of functionality can make short work of capitalization tasks when working with strings. This is primarily thanks to the power of regular expressions because without them, these code examples would have been even longer.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
joshtronic

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.