DEV Community

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

Collapse
 
qm3ster profile image
Mihail Malo • Edited

This is probably the best multi-word solution.
I totally forgot about \b, it is excellent.
I totally emulated it with /(?:^|\s)\w/, since capitalizing the whitespace doesn't do anything, but this is just so much better!

Does the i flag improve performance and not harm it though?

I'd potentially hoist the regex and callback constructions out of the function, although that may be crazy to do.

Thread Thread
 
diek profile image
diek

Hi, the i doesn't does anything in this case, it is my mania of writing it always. The mdn's docu says this about \w:

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_]

So \w is case insesitive already.

Thread Thread
 
qm3ster profile image
Mihail Malo • Edited

OH NO

'mi ke$ha'.toLowerCase().replace(/\b\w/gi, c => c.toUpperCase())
//> "Mi Ke$Ha"

:'(

Thread Thread
 
diek profile image
diek

That was expected, which result do you wanted?

Thread Thread
 
qm3ster profile image
Mihail Malo

Try my honestly unironically inferior regex and see:

'mi ke$ha'.toLowerCase().replace(/(?:^|\s)\w/g, c => c.toUpperCase())