How to Capitalize a String with 1 Line of JavaScript

Photo by Joan Gamell on Unsplash

How to Capitalize a String with 1 Line of JavaScript

and Capitalize Every Word in a Sentence

ยท

2 min read

I'll keep this post short and sweet as I gotta run to yoga class soon here! ๐Ÿง˜โ€โ™‚๏ธ

Capitalizing a word in JavaScript is a bit of a pain, because strings are immutable. That is, you CANNOT simply change a character in a string like this:

str = 'javascript';
str[0] = 'J'; //  BIG NO NO

console.log(str);  // => javascript

No worries though, because capitalizing a word can be done in 1 line of code.

Simple function to return a capitalized word

str = "javascript";

// simple arrow function
const capitalize = (str) => str[0].toUpperCase() + str.slice(1);

console.log(capitalize(str)); // => Javascript

Does this make sense?

We're just taking the first character and capitalizing it: str[0].toUpperCase() and combining that with str.slice(1), which is just the string with the first character removed.

Great! Now how do I capitalized an entire sentence?

I'd thought you'd ask that! That's slightly more complex but can also be done on 1 line.

Let's first break it up to make it more readable:

// our function to capitalize a word
const capitalize = (str) => str[0].toUpperCase() + str.slice(1);

const sentence = "yo javascript rocks";

const capitalizedSentence = sentence
.split(' ')
.map(word => capitalize(word))
.join(' ');

console.log(capitalizedSentence) // => Yo Javascript Rocks

Here we are just splitting up the sentence into an array of words, using the map function to capitalize each word, and then converting the array back into a string. ๐Ÿ˜†

We can convert this into a 1 line arrow function that should word with any sentence:

const Capitalize = (str) => str
.split(' ')
.map(word => word[0].toUpperCase() + word.slice(1))
.join(' ');

Hope this helps!

Did you find this article valuable?

Support Amit Mehta by becoming a sponsor. Any amount is appreciated!

ย