There’s many beginner-friendly code challenges that will help you to start thinking more like an engineer. One such challenge is one where you capitalize the first letter of every word in a given string. In this article, we’ll take a look at the prompt and several possible solutions in JavaScript.
The Prompt
Given a function, capitalize, that takes in str as a parameter, return that str with every word capitalized. Try to think of edge cases in your solution (such as no input, the wrong type of input, etc).
The Approach
- Take a look at the prompt again. Jot down or highlight any keywords that you can find in the wording.
- Piece the meaning of the word problem together. Part of the hardest part about doing code challenges is to try to figure out what the problem is asking you to do. Understanding the problem will help you come a long way in being able to solve it.
- Pseudocode out a possible solution. It doesn’t have to be real code (it doesn’t have to be executable in your IDE or browser console – plain English is fine):
Understand what you're given: given a function that takes some sort of input Understand what you need to return: a string What's the first thing you need to do? What are some options I can take, knowing that the input is a string? Is there string methods I can use? How can I look them up if I don't know what they are? What do I do if the input is empty or it's a number or object? Maybe let's start by writing a for loop to loop through the string. What comes next? ... and so on...
Thoroughly break the problem step-by-step. It will help you to think of edge cases – cases where there might be an incorrect input passed or an empty string – and how to break the problem down into logical steps. This is basically your experimentation phase – there are no wrong answers, just thoughts about how to approach the problem. Those thoughts can be misguided or misdirected – that’s how you learn about approaches that won’t work to a problem.
I have found that if I can break down the problem by explaining it out loud, the logic comes to me easier. Your mileage may vary on your approach, but I wanted to at least suggest it in case it works for you! The pseudocode for a small problem like this seems to be a little bit much, but if you practice the concept now, it’ll come easier to you when you are working on significantly harder problems.
The Solutions
Solution #1: split() and for loop with string.replace() and charAt() methods
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>for loop</title> </head> <body> <div id="root"></div> <script async defer> let capitalize = (str) => { let arr = str.split(' '); for(let i = 0; i < arr.length; i++ ) { arr[i] = arr[i].replace(arr[i].charAt(0), arr[i].charAt(0).toUpperCase()); } return arr.join(' '); } let root = document.getElementById('root'); root.innerHTML = JSON.stringify(capitalize('the quick brown fox jumped over the lazy dog')); </script> </body> </html>
In this first solution, we split the string on its spaces. This gives us an arr with each individual word as its own index. Looping over the array gives us the ability to access each string’s personal indexes. We re-assigned the string (the string in this case being arr[i]) at index i to be the outcome of replacing the string character at index 0 (arr[i].charAt(0) with its upper case value. We then rejoined the arr into a string with spaces in between each of the words.
Solution #2: split with map method and slice
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Map</title> </head> <body> <div id="root"></div> <script async defer> let capitalize = (str) => { // split the string on the spaces so that we know what we are working with. let arr = str.split(' ') // make sure there is a space in between the two quotes here //use the map method arr.map((word, index, array) => { array[index] = array[index][0].toUpperCase() + array[index].slice(1); return array[index]; }) console.log(arr) return arr.join(' '); } let root = document.getElementById('root'); root.innerHTML = JSON.stringify(capitalize('the quick brown fox jumped over the lazy dog')); </script> </body> </html>
In this solution, we start off very similarly, but then we use an ES6 array method called map to loop over the array and return new values that capitalizes the first character of each word. It does this by explicitly laying out what we are going to do with the toUpperCase()
method for the first letter, the slice()
method for the rest of the string, and string concatenation to get the new version of the word. We then join the array and return it.
Solution #3: regular expressions
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> </head> <body> <div id="root"></div> <script async defer> let capitalize = (str) => { let regex = /(^|\s)\S/g return str.replace(regex, letter => letter.toUpperCase()); } let root = document.getElementById('root'); root.innerHTML = JSON.stringify(capitalize('the quick brown fox jumped over the lazy dog')); </script> </body> </html>
In this solution, we use a regular expression to look for all non-whitespace characters ( \S ) at either the beginning of the string ( ^ ) or after a whitespace character ( \s ). The g flag on the end means global and it allows us to look for all instances of that pattern. Then we use the replace method to replace that regex pattern with a function that takes that letter and returns it to uppercase.
Final Thoughts
These solutions are by no means the only solutions to this problem. More than likely, as you start to do more of these, you will come up with solutions that may or may not be different than an article or blog post presents. That’s a good thing. It means you’re starting to think like an engineer – and that’s the goal.
Keep at it. In these solutions, edge cases were not handled. What should you do if your argument is empty or is a number? Try to add to the code above by handling those edge cases.
Hint: Use a bang/exclamation point to conditionally find out if str exists. Take a look at the MDN docs to find out if there is a method to find out the type of something when you don’t necessarily know what it is.
One More Thing: Try your hand at the JavaScript Reverse String Code Challenge if you haven’t already!
More Resources to Consider:
Using Regular Expressions in Ruby – This is dedicated to Ruby, but regex for the most part is language agnostic – check it out to learn more about the RegExp syntax in Solution #3.
JavaScript Replace Text: A Step-By-Step Guide – A tutorial dedicated to the replace method, used in Solution #1.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
Hey, nice article, there is a small type though… In the 3rd method it should be square brackets:
let regex = /[^|\s]\S/g
otherwise each word after the space begins with a space 😉