DEV Community

Discussion on: Daily Challenge #190 - capitalizeFirstLast

Collapse
 
willsmart profile image
willsmart • Edited

An easy option is to start off by lowercasing the whole thing...
(JS)

capitalizeFirstLast = s => s.toLowerCase().replace(/\b\w|\w\b/g, c => c.toUpperCase())

Regex matches single letters preceded by a word boundary or followed by a word boundary.

Running through the examples:

[
  "and still i rise",
  "when words fail music speaks",
  "WHAT WE THINK WE BECOME",
  "dIe wITh mEMORIEs nOt dREAMs",
  "hello"
].map(s => `"${s}" -> "${capitalizeFirstLast(s)}"`).join("\n")

>> 

"and still i rise" -> "AnD StilL I RisE"
"when words fail music speaks" -> "WheN WordS FaiL MusiC SpeakS"
"WHAT WE THINK WE BECOME" -> "WhaT WE ThinK WE BecomE"
"dIe wITh mEMORIEs nOt dREAMs" -> "DiE WitH MemorieS NoT DreamS"
"hello" -> "HellO"
Collapse
 
khauri profile image
Khauri

Nice! Super clean.

Collapse
 
willsmart profile image
willsmart

Thanks!