I’m still kind of spoiled by the built in functions in PHP (as well as Ruby and Python for this particular task). Something like capitalizing the first letter of a string is trivial thanks to ucfirst. But in JavaScript, assuming you’re not using php.js, the process is a bit more involved.

To capitalize the first character of a string, you need to isolate the first character from the left of the string, and then concatenate it with the rest of the string.

const lower = 'this is an entirely lowercase string';
const upper = lower.charAt(0).toUpperCase() + lower.substring(1);

And if you are comfortable with regular expressions, you do things this way:

const upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();

And you can even take it one step further by using more modern syntax:

const upper = lower.replace(/^\w/, c => c.toUpperCase());

A bit more code than PHP but it gets the job done!

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: