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 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.
Before getting deeper into Javascript capitalize, let's first understand the term capitalize according to the programming aspects.
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.
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()
It returns the character at a given index in a string.
toUpperCase()
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-
Target the index element, which is supposed to be converted into uppercase. This can be easily done using the charAt() method.
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
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
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
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));
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
Practice by yourself with the help of an online javascript compiler. Now it’s time for some frequently asked questions.
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
Refer to ourguided paths on Coding Ninjas Studioto learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in ourcoursesand refer to themock test andproblems available. Find more such exciting algorithms in our library section, and solve interesting questions on our practice platform Coding Ninjas Studio. Keep Learning.