paulserban.eu

Writing Edition

Paul Serban

Writing, snippets & book notes

Capitalize The First Letter In A Word With JavaScript

Using JavaScript to capitalize the first letter of a string.

Capitalizing the first letter in a string is a common task in programming, Whether you are working on a personal project or developing for a client, you may need to format text in a specific way.

Use Cases

Methods

#1 - charAt, slice, toUpperCase

const word = "hello world";
const firstLetter = word.charAt(0); // => h
const remainingLetters = word.substring(1); // => ello
const capitalFirstLetter = firstLetter.toUpperCase(); // => H
const capitalizedWord = capitalFirstLetter + remainingLetters; // => Hello
const word = "hello world";
const capitalized = `${word.charAt(0).toUpperCase()}${word.slice(1)}`;

#2 - replace and Regular Expressions

const string = "hello world";
const capitalizedString = string.replace(/^\w/, (c) => c.toUpperCase());

#3 - Destructuring and Template Literals

const string = "hello world";
const capitalizedString = `${string[0].toUpperCase()}${string.slice(1)}`;

#4 - split into an Array, map and join into back into a String

const string = "hello world";
const capitalizedString = string
  .split("")
  .map((char, index) => (index === 0 ? char.toUpperCase() : char))
  .join("");

#5 - substr and toUppercase

const string = "hello world";
const capitalizedString = string.substr(0, 1).toUpperCase + string.substr(1);

#6 - slice and toUppercase

const string = "hello world";
const capitalizedString = string.slice(0, 1).toUpperCase + string.slice(1);