Introduction
This is one of the most common programming interview questions that you would have come across. So here we will be seeing how we can capitalize on the first word in a string using 3 different approaches.
Here is the code sample that shows you how to capitalize the first word in a given string.
EXAMPLE 1
- function capitalize(input) {
- var words = input.split(' ');
- var CapitalizedWords = [];
- words.forEach(element => {
- CapitalizedWords.push(element[0].toUpperCase() + element.slice(1, element.length));
- });
- return CapitalizedWords.join(' ');
- }
OUTPUT
Here is a second code sample that shows you how to capitalize on the first word in a given string using an approach where we check for the previous character in a string and capitalize on the current character if the previous character is a space.
EXAMPLE 2
- function capitalize(input) {
- var CapitalizeWords = input[0].toUpperCase();
- for (var i = 1; i <= input.length - 1; i++) {
- let currentCharacter,
- previousCharacter = input[i - 1];
- if (previousCharacter && previousCharacter == ' ') {
- currentCharacter = input[i].toUpperCase();
- } else {
- currentCharacter = input[i];
- }
- CapitalizeWords = CapitalizeWords + currentCharacter;
- }
- return CapitalizeWords;
- }
OUTPUT
Here is another code sample which is shorthand of what we have done above and is achieving the same results using fewer lines of code.
- function capitalize(input) {
- return input.toLowerCase().split(' ').map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(' ');
- }
OUTPUT
I hope you find this blog helpful. Stay tuned for more … Cheers!!