How to Capitalize a Word in JavaScript

JavaScript is a programming language that is used to control the behavior of web pages. It can be used to make words capitalized or lowercase, and it can be used for many other things too. In this blog post, we will discuss how to capitalize a word in JavaScript. We will also go over some methods and examples.

There isn’t a built-in method to capitalize a word, so we have to use others and modify to suit our required output. There are four methods we will use:

  • toUpperCase() – The toUpperCase() method makes the string you give it uppercase.
  • slice() – The slice()⁠method extracts part of a string, returning it as another string without touching the original.
  • charAt() – The String object’s charAt() method returns a new string consisting of the single UTF-16 code unit (a number between 0 and 65535) located at the specified offset into the string.
  • toLowerCase() – The toLowerCase() method converts the string value passed in to all lower case letters.
  • subsrtring() – The substring() method returns the part of the string between the start and end indexes, or the whole of it.

Here are some methods which can capitalize a word:

let output = ''; //no need to redefined for all exmaples
let source = 'WoRD';

output = source.charAt(0).toUpperCase() + source.toLowerCase().slice(1);
output = source[0].toUpperCase() + source.slice(1).toLowerCase();
output = source[0].toUpperCase() + source.substring(1).toLowerCase();
output = source.split('').map((character, index) => index ? character.toLowerCase() : character.toUpperCase()).join('');

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close