w3resource

JavaScript: Capitalize the first letter of a string

JavaScript fundamental (ES6 Syntax): Exercise-263 with Solution

Capitalize First Letter

Write a JavaScript program to capitalize the first letter of a string.

  • Use array destructuring and String.prototype.toUpperCase() to capitalize the first letter of the string.
  • Use Array.prototype.join('') to combine the capitalized first with the ...rest of the characters.
  • Omit the lowerRest argument to keep the rest of the string intact, or set it to true to convert to lowercase.

Sample Solution:

JavaScript Code:

// Define a function 'capitalize' to capitalize the first letter of a string
// and optionally lowercase the rest of the string
const capitalize = ([first, ...rest], lowerRest = false) =>
  // Convert the first character to uppercase and concatenate it with the rest of the string
  first.toUpperCase() + 
  // If 'lowerRest' is true, join the remaining characters and convert them to lowercase,
  // otherwise, join the remaining characters as they are
  (lowerRest ? rest.join('').toLowerCase() : rest.join(''));

// Test the function with different inputs
console.log(capitalize('fooBar')); // Output: "FooBar"
console.log(capitalize('fooBar', true)); // Output: "Foobar"

Output:

FooBar
Foobar

Visual Presentation:

JavaScript Fundamental: Capitalize the first letter of a string.

Flowchart:

flowchart: Capitalize the first letter of a string.

Live Demo:

See the Pen javascript-basic-exercise-263-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that capitalizes the first letter of a given string while leaving the rest unchanged.
  • Write a JavaScript function that trims a string and then converts only its first character to uppercase.
  • Write a JavaScript program that uses regular expressions to identify and capitalize the first letter of a string.
  • Write a JavaScript function that capitalizes the first letter of a sentence and returns the modified string.

Go to:


PREV : Encode String to Base-64.
NEXT : Capitalize First Letters of Words.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.