Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Capitalization
3.
Javascript capitalize
4.
Problem🤔
4.1.
Input
4.2.
Expected Output
4.3.
Explanation
5.
Implementation in Javascript
5.1.
Using charAt(), toUpperCase() and slice() Method
5.1.1.
Algorithm
5.1.2.
Output
5.2.
Using Regex or replace() Method
5.2.1.
Algorithm
5.2.2.
Output
5.3.
Using Bracket Notation
5.3.1.
Algorithm
5.3.2.
Output
5.4.
Using substring
5.4.1.
Algorithm
5.4.2.
Output
5.5.
Check out this article - String slicing in Python
6.
Problem🤔
6.1.
Input
6.2.
Expected Output
6.3.
Explanation
7.
Implementation in Javascript
7.1.
Algorithm
7.2.
Output
8.
Frequently Asked Questions 
8.1.
What is JavaScript Strict Mode?                 
8.2.
What are the properties and methods in JavaScript?
8.3.
What is a type in JavaScript?
8.4.
What are Strings in Javascript?
8.5.
How does indexing start in javascript?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Program to Capitalize First Letter in a String

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Have you ever seen grammatically incorrect letters (capital or small) in a string or a word and want to make that string grammatically error-free? Or have you ever come across some problems in coding where you were asked to capitalize a particular character in a string? 

Today we will learn about Javascript capitalize. We will see different approaches to changing a letter into a lowerCase or an UpperCase.

Javascript capitalize

JavaScript is a lightweight interpreted programming language widely used in front-end development. This programming language adds interactivity to your website, which helps in engaging users. 

So let's understand more about different functions or methods used in Javascript capitalize.

Also Read, Javascript hasOwnProperty

 

Capitalization

Before getting deeper into Javascript capitalize, let's first understand the term capitalize according to the programming aspects. 

word capitalization

Capitalizing in computer programming means conversion of any character present in a string or a word to UpperCase or capital letters as per your requirements. In different programming languages, the capitalization of a letter can be achieved using different methods. Now let's explore the concept of  Javascript capitalize.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Javascript capitalize

Let's say you have to display a list of strings, but you accidentally inserted some capital or small letters at the start or mid of a string. This must be eliminated before being displayed.

When working with strings in Javascript, replacing a lowerCase into an upper case in a given String is one of the common needs. 

Javascript has a variety of built-in methods which helps in converting the first letter of a string into UpperCase or vice versa. We will look at some Javascript programs to perform this task using these methods-

  • charAt() 
charAt() img

It returns the character at a given index in a string.

  • toUpperCase()
toUpperCase() img

As shown in the above image, this function converts all the characters of an input string to uppercase.

slice()

This method slices a given string from a "start" position to the given "end" position.

substring()

The substring() method extracts characters, between two indices (positions), from a string and returns the substring.

replace()

This method searches for a value in a string and replaces it with the correct value.

Problem🤔

Convert the first letter of a String or a word into UpperCase. 

To understand the problem, let's first see an example:

Input

String str = "javascript";

Expected Output

Javascript

Explanation

The example above demonstrate that the str variable contains a string in which the first character is in small letters. To get the correct output, we have to perform these two steps-

  1. Target the index element, which is supposed to be converted into uppercase. This can be easily done using the charAt() method.
  2. Replace the first word with an uppercase letter using the "toUpperCase()" property. And add the rest of the string as it is.

Implementation in Javascript

Using charAt(), toUpperCase() and slice() Method

Algorithm

  • First, we will declare a string with the variable name str.
  • Then, we will initialize the string with some value. 
  • Use the chart() method to extract the string's first character. Here, str.charAt(0); gives ‘c’.
  • Convert the extracted character to uppercase using "toUpperCase()" method. Here, str.charAt(0).toUpperCase(); gives ‘C’.
  • With the help of the slice() method, return the rest of the string and concatenate the string to the capitalized letter using the '+' operator.

The implementation of the above algorithm is given below.

function capitalizeLetter(str) {
 
    // Convert first letter to uppercase
    const capitalizedString = str.charAt(0).toUpperCase() + str.slice(1);
 
    return capitalizedString;
}
 
const str = "coding Ninja";
 
print(capitalizeLetter(str));

Output

output img

Using Regex or replace() Method

In this method, the regular expression (regex) is used to convert the first letter of a string to uppercase.

Algorithm

  • First, we will declare a string with the variable name str and initialize the string with some value. 
  • With the help of the regex pattern, which is /^./ match the first character of a string and replace it with the capitalized letter using replace() and "toUpperCase()" methods.
  • Finally, we will print the string with the capitalized first letter.

The implementation of the above algorithm is given below.

function capitalizeLetter(str) {

    // Convert first letter to uppercase
    const capitalizedString = str.replace(/^./, str[0].toUpperCase());
 
    return capitalizedString;
}
 
const str = "coding Ninja";
 
print(capitalizeLetter(str));

Output

Output

Using Bracket Notation

Algorithm

  • First, we will declare a string with the variable name str and initialize the string with some value. 
  • This time we will directly use the bracket notation to target the first index of the string, and then we will convert the first element into UpperCase.
  • Finally, we will print the required string.

The implementation of the above algorithm is given below.

function capitalizeLetter(str) {

    //Capitalizing the first letter of a string.
    return str[0].toUpperCase() + str.slice(1).toLowerCase(); 
} 
const str = "coding is so easy!"; 
print(capitalizeLetter(str));

Output

Output

Using substring

Algorithm

  • First, we will declare a string with the variable name str and initialize the string with some value. 
  • This time we will directly use the substring method instead of slice() method to target the rest of the string, and then we will concatenate it to the first element of the string.
  • Finally, we will print the required string.
function capitalizeLetter(str) {
 
    // Capitalize first letter of a string to uppercase.
     return str[0].toUpperCase() + str.substring(1).toLowerCase();
 
}
 
const str = "coding is so easy!";
 
print(capitalizeLetter(str));

Output

Output

Check out this article - String slicing in Python

Problem🤔

Capitalize the first letter of each word in a string

To understand the problem, let's first see an example:

Input

String str = "'i love coding ninja";

Expected Output

I Love Coding Ninja

Explanation

The example above demonstrates that the str variable contains a string in which the first character of all the words are in small letters. To achieve the capital letter of each word, we will split the words from the string and store them in a newly formed array, and then use some methods to print the required string. 

Implementation in Javascript

Algorithm

  • First, we will declare two strings with the variable name str1 and str2
  • Initialize the string str1 with some value. 
  • Using split() method, we will split the string into an array of strings whenever a blank space is encountered.
  • Using for loop, iterate over each element of the array and capiltalize the first letter of each array using charAt() and toUpperCase() methods.
  •  Finally, we will print the string with the capitalized first letter.
const str1 = 'i love coding!';
 
//split the above string into arrays 
const array = str1.split(" ");
 
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < array.length; i++) {
    array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1);
}
//Now join all the elements of the array back into a string 
//using a blank space as a separator  
const str2 = array.join(" ");
print(str2);

Output

output

Practice by yourself with the help of an online javascript compiler. Now it’s time for some frequently asked questions.

FAQs

   

Frequently Asked Questions 

What is JavaScript Strict Mode?                 

JavaScript Strict Mode is a method to switch to a more secure and cleaner version of JavaScript. Here, the JavaScript compiler does not ignore minor syntactical errors.

What are the properties and methods in JavaScript?

A property is a relation between the name (or key) and a value, while an object is a collection of properties. A property can have a function as its value, which is known as a method.

What is a type in JavaScript?

The types control how much memory is allocated to store a value. The type also defines the operations and methods that can be applied to a value. String, number, undefined, null, boolean, and symbol are the six primitive types in JavaScript.

What are Strings in Javascript?

Strings in javascript are sequences of characters, numbers, and alphabets. Strings in javascript are immutable.

How does indexing start in javascript?

Indexing of strings in javascript starts with 0. It starts from left to right.

Conclusion

This article taught us how to capitalize letters in a string. We started with understanding what Javascript capitalize is. We further discussed different methods to get rid of the lowerCase letters using Javascript capitalize. Then we finally addressed each and every method in Javascript along with the coded examples. For enhancement of your knowledge, you can also refer to other articles in Java as well 

 

Recommended problems -

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Find more such exciting algorithms in our library section, and solve interesting questions on our practice platform Coding Ninjas Studio. Keep Learning.

Happy Coding!

Previous article
Object Oriented Programming In JavaScript
Next article
Hello World Program in JavaScript
Live masterclass