How to make first letter of a string uppercase in JavaScript ?
In this article, we will convert the first letter of a string to uppercase in Javascript. There are a number of ways to capitalize the first letter of the string in JavaScript.
- Using toUpperCase() method
- Using slice() method
- Using charAt() method
- Using replace() method
JavaScript toUpperCase() Function: This function applies on a string and changes all letters to uppercase.
Syntax:
string.toUpperCase()
JavaScript slice() Function: This function applies to a string and slices it according to the passed parameter.
Syntax:
string.slice(start, end)
Example: This example uses the slice() method to convert the first letter to uppercase.
Javascript
function capitalizeFLetter() { let string = 'geeksforgeeks' ; console.log(string[0].toUpperCase() + string.slice(1)); } capitalizeFLetter() |
Geeksforgeeks
JavaScript charAt() Function: This charAt() function returns the character at a given position in the string.
Syntax:
string.charAt(index)
Example: This example uses charAT() method to make the first letter of a string uppercase.
Javascript
function capitalizeFLetter() { let string = 'geeksforgeeks' ; console.log(string.charAt(0).toUpperCase() + string.slice(1)); } capitalizeFLetter() |
Geeksforgeeks
JavaScript replace() Function: This is a built-in function in JavaScript that is used to replace a slice of a string with another string or a regular expression. The original string will not be affected.
Syntax:
str.replace(A, B)
The below examples show the conversion to uppercase using the above-described methods.
Example: This example uses string.replace() method to make the first letter of a string uppercase.
Javascript
function capitalizeFLetter() { let string = 'geeksforgeeks' ; console.log(string.replace(/^./, string[0].toUpperCase())); } capitalizeFLetter() |
Geeksforgeeks
Please Login to comment...