How to capitalize last letter of string - JS

Mo Ibra

Mo Ibra

Dec 22, 2022

In this article we will learn how capitalize last letter of a string.

It is very common capitalize last letter of a string in JavaScript.


Problem

Now we have a problem, which is that we want to capitalize the last letter of the word, and this can happen a lot in the world of programming.

Now let's imagine we have a string like this:

"hello world"

And we want to capitalize the last character for some reason, so that the string becomes like this:

"hello worlD"

How to solve this problem?

You think the problem is easy, right? But in fact, it is not very easy because there is no function that capitalizes only the last character in the string in JavaScript.

So we will make a solution by ourselves.

The solution will be as follows

  • Use the charAt(str.length - 1) method to get last letter
  • We will capitalize last letter with toUppercase() method
  • Use the slice(0, str.length - 1) method to slice the string leaving the last character.
  • Finally, We will concatenate the output of both functions.

Solution:

Before writing the full code, I will write line by line so that you understand exactly what is happening.

First we have to get the last letter to be capitalized, right?

// String
const string = "hello world";

// Get last Letter
const last = string.charAt(string.length - 1);

// Result:
console.log(last);

Output

d

Now let's capitalize that letter

// String
const string = "hello world";

// last letter
const last = string.charAt(string.length - 1);

// Capital last letter
const capital = last.toUpperCase();

// Result:
console.log(capital);

Output

D

Now we get the string from the beginning to the penultimate letter.

// String
const string = "hello world";

// last letter
const last = string.charAt(string.length - 1);

// Capital last letter
const capital = last.toUpperCase();

// Rest of string
const rest = string.slice(0, string.length - 1)

// Result
console.log(rest);

Output

hello worl

Now we will concatenate uppercase letter with rest of string.

Full code

// String
const string = "hello world";

// last letter
const last = string.charAt(string.length - 1);

// Capital last letter
const capital = last.toUpperCase();

// Rest of string
const rest = string.slice(0, string.length - 1)

// Concatination
const result = rest + capital;

// Result:
console.log(result);

Output

hello worlD

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: