Would you like to know how to convert the first letter of a string into capital letters? Let’s explore the possible pathways.
1) Using slice
Convert the first letter of a string into capital letters using the toUpperCase() method.
Extract the remaining characters from a string with slice() method.
Combining the two results will return the converted string.
const word = 'react';
const capitalizedWord = word[0].toUpperCase() + word.slice(1);
2) Using substr
Extract the first letter from a string using substr() method and change it into upper case using toUpperCase() method.
Extract the remaining characters from a string with substr() method.
Combining the two results will return the converted string.
const name = 'angular';
const capitalizedName = name.substr(0,1).toUpperCase() + name.substr(1, name.length);
3) Using split
Splitting the string into separate characters and storing them as an array using split() method.
Convert the first item of an array into capital letters using the toUpperCase() method.
Converting the array of items into string using the join() method.
const text = 'vue';
const capitalizedText = text.split('');
capitalizedText[0] = capitalizedText[0].toUpperCase();
capitalizedText.join('');
4) Using spread
Splitting the string into separate characters and storing them as an array using spread operator.
Convert the first item of an array into capital letters using the toUpperCase() method.
Converting the array of items into string using the join() method.
const channelName = 'codingsparkles';
const convertedName = [...channelName];
convertedName[0] = convertedName[0].toUpperCase();
convertedName.join('');
Sample work used with the above code snippets can be found in the following codepen.
That’s all about this blog post friends. Share your ideas on this topic.
I hope this will be useful for you, do you think something is very similar, simply share this with your friends!