Convert first letters of a string to uppercase in JavaScript
In this tutorial, we will learn how to convert the first letters of a string to uppercase in JavaScript.
Variables used in code
- str – string
const str = "This is a Tutorial in CodeSpeedy"
Method 1
We’ll divide the string into an array of words, capitalize the first letter of each word, and then join the array of words back together.
Inbuilt Methods used
- split() – split a string to array
- join() – join array elements to string
- toUpperCase() – convert string to uppercase
let wordArray = str.split(" ") for(let i = 0; i < wordArray.length; i++) { if(wordArray[i] !== ""){ wordArray[i] = wordArray[i][0].toUpperCase() + wordArray[i].slice(1,) } } let uppercaseString = wordArray.join(" ") console.log(uppercaseString)
Method 2
Instead of converting a string to an array and then back to a string. This method works directly with string.
Inbuilt Methods used
- charAt() – get the char at required position
- slice() – slice a string
- indexOf() – find the index of a substring
- toUpperCase() – convert string to uppercase
function FirstLettersToUppercase(str) { if (str != "") { str = str.charAt(0).toUpperCase() + str.slice(1) } let i = 0 while(i !== -1 & i < str.length) { let index = str.indexOf(" ",i) if(index !== -1 & str.charAt(index+1) !== " ") { str = str.slice(0,index+1) + str.charAt(index+1).toUpperCase() + str.slice(index+2) i = index + 1 } else if(index === -1){ i = index } else{ i = index + 1 } } return str } let uppercaseString = FirstLettersToUppercase(str) console.log(uppercaseString)
Output
"This Is A Tutorial In CodeSpeedy"
Also read: Convert string to array in JavaScript
Leave a Reply