DEV Community

Discussion on: Web Basics: How to Capitalize a Word in JavaScript

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I have a function exactly do that. (I use this function for 3 years. I just changed for new ES standards)

const capitalize = (str) => {
  return str
    .toLowerCase()
    .split(' ')
    .map(strWord => strWord.substring(0, 1).toUpperCase() + strWord.substring(1, strWord.length))
    .join(' ')
}

In this example, this function firstly takes a string.

After that, the whole string will be lowercase.

After that, the string will be split with empty spaces. (Ex: I HAVE NO IDEA)

Now, we have words array. I use the map method to manipulate the array.

We'll take the first letter of the word. This letter will be uppercase. The others will be lowercase.

If you know how the substring method works, you won't be confused.

And the last one, we'll concatenate the words to create our new string. That's all.

Collapse
 
samanthaming profile image
Samantha Ming

Nice use to map! And awesome explanation with it! Thanks for sharing 🤓

Collapse
 
reegodev profile image
Matteo Rigon • Edited
const capitalize = (str) => {
    return str
        .split('')
        .map((c,i) => i ? c.toLowerCase() : c.toUpperCase())
        .join('')
}

Might be more performant since you have to loop the array anyway

Collapse
 
samanthaming profile image
Samantha Ming

Woo, I love this solution! Nice use to the falsy value to check the first character (cause 0 is false). Thanks for sharing 💯

Collapse
 
qm3ster profile image
Mihail Malo • Edited

You can just map on the string :v

const capitalize = str =>
  Array.prototype.map
    .call(str, (c, i) => i ? c.toLowerCase() : c.toUpperCase())
    .join('')

But no, it's most likely not going to be performant (even like this), because it involves indexing into every character instead of handing the underlying native string to the native method.

Worse yet, .split('') and such don't play well with composite Unicode graphemes.

Collapse
 
qm3ster profile image
Mihail Malo • Edited

You can omit the second argument in substring, substr and slice to get the rest of the string until the end.
You can also use charAt(0) or even .charAt() to get the first char instead of a slicing method.

const capitalize = str => str
  .toLowerCase()
  .split(' ')
  .map(strWord => strWord.charAt().toUpperCase() + strWord.slice(1))
  .join(' ')