For this challenge, you will have to write a function called capitalizeFirstLast
or capitalize_first_last
. This function will capitalize the first and last letter of each word, and lowercase what is in between.
capitalizeFirstLast "and still i rise" -- "AnD StilL I RisE"
Rules:
- The function will take a single parameter, which will be a string.
- The string can contain words separated by a single space.
- Words are made of letters from the ASCII range only.
- The function should return a string.
- Only the first and last letters are uppercased.
- All the other letters should be lowercased.
Examples:
capitalizeFirstLast "and still i rise" -- "AnD StilL I RisE"
capitalizeFirstLast "when words fail music speaks" -- "WheN WordS FaiL MusiC SpeakS"
capitalizeFirstLast "WHAT WE THINK WE BECOME" -- "WhaT WE ThinK WE BecomE"
capitalizeFirstLast "dIe wITh mEMORIEs nOt dREAMs" -- "DiE WitH MemorieS NoT DreamS"
capitalizeFirstLast "hello" -- "HellO"
Good luck!
This challenge comes from aminnairi here on DEV. Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (24)
An easy option is to start off by lowercasing the whole thing...
(JS)
Regex matches single letters preceded by a word boundary or followed by a word boundary.
Running through the examples:
Nice! Super clean.
Thanks!
Javascript + Regex "One" liner.
Click here if you're curious what the regular expression does
First try in Ruby, I think this can be done without splitting and rejoining.
The most straightforward way to fix this is probably to do something as:
but probably there are better ways to do this :P
EDIT: Ofc some tuning is required if we also accept punctuation and, numbers or any other characters of sort, but the requirements state letters, so...
I think there are a couple mistakes in your solution.
In your
capitalizeFirstLastInWord
function, you are using the variableentry
. I think you meantword
?And in your
capitalizeFirstLast
function, you are using an undefined variablefixedWord
. Maybe this was the return value of your previous function call?Other than that, I really like how you used the
reduce
method to solve this one!You are 100% right, I did some last-minute refactoring and I was a bit distracted! :P
I will edit it for future readers :)
About the
reduce
part: The idea came because last year I was able to work with anawesome team which enforced very good practices & a very cool "implementation"
of functional programming, I miss that team a lot!
C++
Python one liner
First & Fast & Last try with JS
Cool, many ways of doing this.
This is what I came up with:
Python
Something like this with JS
One letter words don't pass. Try
and still i rise
you will getAnD StilL II RisE
Came up with this Elm solution while I was procrastinating at work today:
Not overly different from the other solutions here, but neat nonetheless.