Hone logo
Hone
Problems

Capitalize the First Letter of a String in JavaScript

This challenge focuses on a common string manipulation task: capitalizing the first letter of a string. This is a fundamental skill useful in many applications, from formatting user input to generating titles and headings. Your task is to write a JavaScript function that takes a string as input and returns a new string with the first letter capitalized, while leaving the rest of the string unchanged.

Problem Description

You need to create a JavaScript function named capitalizeFirstLetter that accepts a single string argument. The function should return a new string where the first character of the input string is capitalized, and all other characters remain in their original case. If the input string is empty, the function should return an empty string. The function should handle strings containing spaces and other characters correctly.

Key Requirements:

  • The function must be named capitalizeFirstLetter.
  • It must accept a single string argument.
  • It must return a new string, not modify the original.
  • It must capitalize only the first letter.
  • It must handle empty strings gracefully.

Expected Behavior:

The function should correctly capitalize the first letter of various strings, including those with spaces, numbers, and special characters.

Edge Cases to Consider:

  • Empty string input.
  • String with a single character.
  • String starting with a space.
  • String containing only non-alphabetic characters.
  • Strings with mixed case.

Examples

Example 1:

Input: "hello world"
Output: "Hello world"
Explanation: The first letter 'h' is capitalized, and the rest of the string remains unchanged.

Example 2:

Input: "javascript"
Output: "Javascript"
Explanation: The first letter 'j' is capitalized, and the rest of the string remains unchanged.

Example 3:

Input: ""
Output: ""
Explanation: An empty string is returned as input.

Example 4:

Input: "  leading spaces"
Output: "  leading spaces"
Explanation: The leading spaces are preserved, and the first non-space character is capitalized.

Example 5:

Input: "123abc"
Output: "123abc"
Explanation: The first character is a number, so no capitalization occurs.

Constraints

  • The input string will be a standard JavaScript string.
  • The function must return a string.
  • The function should be efficient enough to handle strings of reasonable length (up to 1000 characters). While performance isn't the primary focus, avoid unnecessarily complex or inefficient algorithms.

Notes

Consider using string methods like charAt(), toUpperCase(), and substring() or slice() to achieve the desired result. Remember that strings in JavaScript are immutable, so you'll need to create a new string to return the capitalized version. Think about how to handle the edge case of an empty string before attempting any capitalization.

Loading editor...
javascript