FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Capitalize Words

Capitalize Words

easy
By FrontendAtlas Editorial · Updated Jan 30, 2026
Capitalize the first letter of every word while preserving spacing. Handle multiple spaces and punctuation without collapsing the original string, and keep non-letter characters intact. This tests string parsing and careful output formatting. Concepts: strings, transforms, arrays, iteration.

Arguments

  • sentence: string — A sentence consisting of one or more words separated by spaces. May contain leading, trailing, or multiple spaces between words.

Returns

string — A new string where each word starts with an uppercase letter and the rest of the word is lowercase. Returns '' for an empty string.
Examples
// Basic examples

capitalizeWords('hello world') // => 'Hello World'

capitalizeWords('javascript is fun') // => 'Javascript Is Fun'

// Handles extra spaces

capitalizeWords('  welcome   to  earth  ') // => '  Welcome   To  Earth  '

// Empty string

capitalizeWords('') // => ''

Solution

Overview

Goal: ensure each word in a sentence starts with an uppercase letter while preserving spacing and keeping the rest of the letters lowercase. If the input is empty, return ''. This builds practical mastery over string splitting, mapping, joining, and basic character processing. Key concepts: strings, transforms, arrays.

1

Approach 1: Split–Map–Join (clean and readable)

Idea: split the sentence into parts by spaces, capitalize the first letter of each non-empty part, and then join them back together.

How it works:

  1. If sentence is falsy (for example, an empty string), return ''.
  2. Use .split(' ') to break the sentence into an array of substrings separated by single spaces.
  3. For each element word in the array, if word is an empty string (extra space), leave it as is; otherwise build word[0].toUpperCase() + word.slice(1).toLowerCase().
  4. Join the transformed array back into a string with ' ' as the separator.
  5. Return the final joined string.

Why use it: clear logic, preserves multiple spaces exactly as they are, and doesn’t require regex — a straightforward approach for readability and maintainability.

export default function capitalizeWords(sentence) {
  if (!sentence) return '';
  return sentence
    .split(' ')
    .map(word => {
      if (!word) return word;
      return word[0].toUpperCase() + word.slice(1).toLowerCase();
    })
    .join(' ');
}
export default function capitalizeWords(sentence: string): string {
  if (!sentence) return '';
  return sentence
    .split(' ')
    .map(word => {
      if (!word) return word;
      return word[0].toUpperCase() + word.slice(1).toLowerCase();
    })
    .join(' ');
}
2

Approach 2: Character iteration (manual traversal)

Idea: iterate through each character and capitalize when the previous character was a space.

How it works:

  1. If sentence is falsy, return ''.
  2. Initialize an empty string result = '' and a boolean flag capitalizeNext = true.
  3. For each character ch in sentence, if ch === ' ', append it to result and set capitalizeNext = true; otherwise, if capitalizeNext is true, append ch.toUpperCase() and set capitalizeNext = false, and if it is false, append ch.toLowerCase().
  4. After processing all characters, return result.

Why use it: avoids splitting and joining, and gives fine-grained control over character-by-character behavior. Efficient for long strings and useful when you want to extend the logic (for example, treat other delimiters as word boundaries).

export default function capitalizeWords(sentence) {
  if (!sentence) return '';
  let result = '';
  let capitalizeNext = true;

  for (const ch of sentence) {
    if (ch === ' ') {
      result += ch;
      capitalizeNext = true;
    } else if (capitalizeNext) {
      result += ch.toUpperCase();
      capitalizeNext = false;
    } else {
      result += ch.toLowerCase();
    }
  }

  return result;
}
export default function capitalizeWords(sentence: string): string {
  if (!sentence) return '';
  let result = '';
  let capitalizeNext = true;

  for (const ch of sentence) {
    if (ch === ' ') {
      result += ch;
      capitalizeNext = true;
    } else if (capitalizeNext) {
      result += ch.toUpperCase();
      capitalizeNext = false;
    } else {
      result += ch.toLowerCase();
    }
  }

  return result;
}

Notes & Pitfalls

Pitfalls
  • Avoid trimming spaces — leading, trailing, and repeated spaces must be preserved.
  • Punctuation and digits are treated as part of a word; only the first character after a space is uppercased.
  • Always lowercase the rest of each word to normalize mixed casing.
Edge cases
  • Empty string → `''`.
  • Extra spaces between words → preserved exactly.
  • Already title-cased input → unchanged.
  • Mixed casing → normalized to Title Case (e.g. `jaVaScript IS fUn` → `Javascript Is Fun`).
Techniques
  • Using `.split()`, `.map()`, and `.join()` for immutable string transformations.
  • String iteration and character-based logic.
  • Applying capitalization rules based on simple word boundaries (spaces).

Resources

  • MDN – String.prototype.split()
  • MDN – String.prototype.toUpperCase()

Similar questions

Remove DuplicateseasyCheck if Two Arrays Are EqualeasyFlatten One Leveleasy

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
72 / 88Next →→