How to Capitalize a Word in JavaScript: Explained With Examples

by | JavaScript

A common task in Javascript you will encounter is manipulating text or strings in various ways, such as capitalization. Capitalizing words in JavaScript can greatly enhance the readability and presentation of text on websites and applications.

To capitalize words in JavaScript, developers can use the built-in string method toUpperCase(). By combining toUpperCase() with other string manipulation methods such as charAt() and slice(), developers can effortlessly capitalize the first letter of each word in a given string.

But, there’s more to it.

You need to be doing things properly.

In this article, we’ll teach you how to use these methods and others to capitalize words in JavaScript.

By using these methods, you’ll be able to effectively manipulate and present text in your applications, providing a polished and professional user experience.

Let’s dive in!

How to Capitalize a Word in JavaScript

What Are JavaScript Strings?

JavaScript strings are sequences of characters that can include a combination of letters, digits, symbols, and spaces.

Strings can be manipulated in various ways, such as converting them to uppercase or lowercase, capitalizing specific words or characters, and inserting or removing symbols.

To declare a string in JavaScript, you can use single or double quotes like so:

let exampleString1 = "Hello, World!";
let exampleString2 = 'Hello again, World!';

Output:

Ever method converts the output to: Hello world

When working with strings in JavaScript, you can leverage certain built-in methods and properties that apply to string objects.

Below are a few common methods that you might find useful:

  • toUpperCase() – Converts all the characters of a string to uppercase letters.
  • toLowerCase() – Converts all the characters of a string to lowercase letters.
  • charAt() – Retrieves the character at a specified position in a string.
  • slice() – Extracts a section of a string and returns it as a new string.
  • indexOf() – Returns the index within the calling string of the first occurrence of the specified value. If the value isn’t found, it returns -1.

Here’s an example of using these methods in JavaScript:

console.log(exampleString1.toUpperCase())
console.log(exampleString2.toLowerCase())
console.log(exampleString1.charAt(3))
console.log(exampleString2.slice(2))
console.log(exampleString1.indexOf('w'))
console.log(exampleString1.indexOf('W'))

Output:

Using functions on string converted to lowercase or uppercase

Understanding how to manipulate strings in JavaScript is essential as it allows you to make text-based changes to the content displayed on your web pages or collected via user input.

Now that we’ve gone over the basics, let’s take a look at how you can use this knowledge to capitalize a single word in JavaScript in the next section!

How to Capitalize a Single Word in JavaScript

In JavaScript, capitalizing a word might seem like a straightforward task, but there are nuances to consider. Whether you’re working with user input or manipulating text for display, knowing how to capitalize words properly can enhance readability and data consistency.

In this section, we’ll explore various methods to capitalize the first letter of a word, covering both native JavaScript functions and custom solutions. By the end, you’ll have a toolkit of techniques for capitalizing words in any JavaScript project.

1. Using String Indexing and the Slice() Function

In JavaScript, you can capitalize the first letter of a word by using the toUpperCase() method on a specific character within the string. Here’s a step-by-step example of how to do this:

  • Get the first character of the original string and convert it to uppercase using toUpperCase().
  • Slice the rest of the string from the second character onward.
  • Combine the uppercase first character with the sliced string.

Now, let’s write a JavaScript program to demonstrate this process:

const word = "lovely";

const capitalizedWord = word[0].toUpperCase() + word.slice(1);
console.log(capitalizedWord);

Output:

Example method returns a single word

In the above program, we take the first letter (L) in the ‘lovely’ and capitalize it using string indexing and the toUpperCase() function.

Next, we slice off the first letter and return the rest of the word using the slice() function. Finally, we combine the capitalized first letter and the rest of the string to give the final capitalizedword, which is “Lovely.”

Now, let’s modularize our program by creating a capitalize function that accepts a word as input and returns the capitalized version.

Here’s how you can create this function:

function capitalize(word) {
  return word[0].toUpperCase() + word.slice(1);
}

const capitalizedWord = capitalize("lovely");
console.log(capitalizedWord)

Output:

Lovely

With the above capitalize function, you can easily capitalize any word by passing it as an argument. This provides a reusable and clean approach for capitalizing single words in JavaScript.

2. Using the charAt() and the Substring Function

This next method is quite similar to the first one. Let’s break it down step-by-step:

  • First, we extract the first letter of the word using the charAt() function.
  • After this, we capitalize the first letter with the toUpperCase() function.
  • Next, we slice off the remaining part of the word using the substring() function.
  • Finally, we combine these two words together.

Now, let’s rewrite our capitalize function as an arrow function using this method:

let capitalize = (word) => word.charAt(0).toUpperCase() + word.substring(1);

const capitalizedWord = capitalize("brazil");
console.log(capitalizedWord);

Output:

Using an arrow function returns capitalized word

In the above solution, the charAt() function takes the place of the string indexing we saw in the previous solution. Some people prefer using the charAt() function because the indexing used to have problems on old browsers like Internet Explorer 7.

3. Using Regular Expressions

You can also capitalize a word in JavaScript using regular expressions and the replace() function. The regular expression captures the first character in the word and replaces it with an uppercase version of the letter.

Let’s implement this in our capitalize function.

function capitalize(word) {
  return word.replace(/^./, word[0].toUpperCase());
}

const capitalizedWord = capitalize("america");
console.log(capitalizedWord);

Output:

America

In the code above, we capture the first letter using the regex syntax /^./. Then the toUpperCase() function converts the first character into a capital letter.

Finally, we replace the first letter with the capital letter with the aid of the replace() function.

How to Capitalize Each Word in a JavaScript String

In JavaScript, capitalizing the first letter of all the words of a string can be achieved efficiently using various methods. Let’s look at them:

1. Using the Split Method

We can use the split() function in conjunction with some of the methods we discussed in the previous section to capitalize each word in a string.

Here’s how:

  • First, we split the string into an array of individual words using the split() function.
  • Using a for loop, we go over each word in the array and capitalize their first letter using one of the methods from the previous section.
  • Next, we join the words in the array back together to form a single string with the join() function.

Let’s see this in practice:

function capitalizeEachWord(string){
    const str_arr = string.split(' ')

    for(i = 0; i < str_arr.length; i++){
        str_arr[i] = str_arr[i][0].toUpperCase() + str_arr[i].slice(1)
    }
    return str_arr.join(' ')
}

let word = 'i love new york'
console.log(capitalizeEachWord(word))

Output:

Splitting up the sentence with var i

As we can see above, this function splits the sentence into individual words, capitalizes the words separately, and then joins them back together. It also works on multiline strings.

2. Using Regular Expressions

Another approach for capitalizing each word in a sentence is to combine Regular Expressions (regex) and string manipulation functions. To achieve this, we can create a function that takes in a string as input, detects each word using a regular expression, and capitalizes it.

Let’s examine a simple example utilizing regex in conjunction with string manipulation functions:

function capitalizeEachWord(str) {
  return str.replace(/\w\S*/g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
}

const word = 'take me home, country roads'

In this function, the regex pattern \w\S* is used to capture each word in the input string. The replace() function then applies a callback on each of these matches.

Within the callback function, the following steps are performed:

  1. The charAt() function is used to extract the first character of each word (e.g., txt.charAt(0)).
  2. The extracted first character is converted to uppercase using toUpperCase().
  3. The substr() function is employed to obtain the remaining part of the word, starting from the second character onwards (e.g., txt.substr(1)).
  4. The remainder of the word is converted to lowercase using toLowerCase().
  5. Finally, the modified word is returned with its first letter capitalized and remaining letters in lowercase.

The capitalizeEachWord() function can be called with any string as its parameter, and it will output the capitalized string:

console.log(capitalizeEachWord("this is an example string"));

Output:

This Is An Example String

In summary, capitalizing each word in a JavaScript string can be easily accomplished using regex and a combination of string manipulation functions like toUpperCase() and toLowerCase(). The provided example function should serve as a solid starting point for implementing this functionality in your code.

3. Using CSS text-transform

The text-transform property in CSS is a simple way to change the capitalization of text. It has the following syntax:

selector {
  text-transform: value;
}

Where value can be capitalize, uppercase, lowercase, or none. For example, if you want to capitalize the first letter of each word in a paragraph element, you can write:

p {
  text-transform: capitalize;
}

This approach is suitable when you want to change the appearance of text for display purposes only.

Common Mistakes When Capitalizing Words in JavaScript

Fixing bugs in Javascript

When working with JavaScript to capitalize words, you might occasionally encounter some issues or common mistakes. In this section, we’ll discuss some of these challenges to help you address them in your code.

A common mistake when capitalizing words is to unintentionally convert the entire string to uppercase letters, rather than just the first letter of each word. This often occurs when using the toUpperCase() method without properly extracting the target letters.

Ensure that you’re using the right combination of string methods, such as charAt(), slice(), and toUpperCase() to perform the capitalization correctly.

Also, these conversion methods only work for string datatypes. So, you will need to make sure you are only converting string instances to uppercase to avoid errors.

Bear in mind that when you are working with sentences, you might encounter words with punctuation and special characters.

For instance, in phrases like “hello, world!”, you need to account for the comma as well. Using regular expressions with the replace() method can be a helpful approach in such cases — especially when it comes to handling multiple word delimiters efficiently.

Lastly, remember that JavaScript is case-sensitive. It is crucial to use the correct capitalization for method names and variables in your code.

For example, if you mix lower and upper-case letters between method names like ToUpper(), tolowercase(), or for variables like str, STR, JavaScript will not recognize them correctly, leading to errors in your program.

Incorrect methods

Final Thoughts

As you delve into the world of JavaScript, understanding how to capitalize words is a small yet impactful skill that can greatly improve the clarity and aesthetics of your code.

By implementing these techniques, you’ll be able to handle and display texts elegantly. We hope that this newfound proficiency enables you to confidently tackle capitalization challenges in your JavaScript projects!

If you loved this article, be sure to check out another great piece on TypeScript Date: Explained With Examples. And if you’d like to learn more about how programming is going to evolve in the age of AI, check out our YouTube playlist below:

Frequently Asked Questions

What’s the best way to make the first letter uppercase in JavaScript?

The fastest and most straightforward method to capitalize the first letter of a string in JavaScript involves using charAt() and slice():

function capitalizeFirstLetter(str) {
  return str[0].toUpperCase() + str.slice(1);
}

Is there a built-in method for capitalizing words in JavaScript?

JavaScript does not have a built-in method for capitalizing words, but you can use the techniques demonstrated in the previous answers to achieve this behavior.

How can I capitalize a word using ES6 syntax in JavaScript?

To capitalize a word using ES6 syntax, you can employ template literals and arrow functions:

const capitalizeFirstLetter = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

How do I capitalize the first letter in TypeScript with Angular?

In TypeScript with Angular, you can create a custom pipe to capitalize the first letter of a string. Here’s an example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

Once the custom pipe is defined, you can use it in your Angular templates like this:

<p>{{ someString | capitalize }}</p>

Related Posts