DEV Community

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

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.