JavaScript: Letter Capitalize

  • Post category:JavaScript

JavaScript: Letter Capitalize

One common coding interview question is to capitalize the first letter of each word in a given string. This task can be achieved using JavaScript by following a few steps. Let’s dive into the solution with some code examples.

Approach 1: Using a combination of string methods and loops

To capitalize the first letter of each word, we can follow these steps:

  1. Split the string into an array of words using the split() method.
  2. Loop through each word in the array.
  3. Capitalize the first letter of each word using the toUpperCase() method on the first character.
  4. Concatenate the capitalized first letter with the remaining characters of the word using the slice() method.
  5. Join the array of words back into a string using the join() method.

Here’s an implementation of this approach:

function capitalizeWords(string) {
  const words = string.split(' ');
  const capitalizedWords = [];

  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    const capitalizedWord = word.charAt(0).toUpperCase() + word.slice(1);
    capitalizedWords.push(capitalizedWord);
  }

  const result = capitalizedWords.join(' ');
  return result;
}

// Example usage:
const inputString = "hello world";
const capitalizedString = capitalizeWords(inputString);
console.log(capitalizedString); // Output: "Hello World"

This approach works well for most cases when the words in the string are separated by spaces. However, it does not handle cases where there are multiple spaces or other non-alphabetic characters between words.

Approach 2: Using regular expressions

To handle cases with multiple spaces or other non-alphabetic characters between words, we can use a regular expression. The regular expression will match the first character of each word and then we can use the replace() method to capitalize it.

function capitalizeWords(string) {
  return string.replace(/\b\w/g, match => match.toUpperCase());
}

// Example usage:
const inputString = "hello   world";
const capitalizedString = capitalizeWords(inputString);
console.log(capitalizedString); // Output: "Hello   World"

In this approach, the regular expression \b\w matches the first character of each word. The replace() method is used with a callback function that takes each match and converts it to uppercase.

Conclusion

In this article, we have explored two approaches to capitalize the first letter of each word in a given string using JavaScript. The first approach uses a combination of string methods and loops, while the second approach leverages regular expressions. Both approaches have their advantages and can be used depending on specific requirements.

Remember to consider edge cases, such as punctuation marks or non-alphabetic characters at the start of a word, that may require additional handling.