Learn how to convert a string to uppercase in javascript.
There are different ways in which we can convert the string to uppercase in javascript. We will see how to convert single, multiple or all the characters of the string to the uppercase.
Using string’s toUpperCase()
method.
toUpperCase()
method only converts the alphabets to the uppercase.
let str = 'abcdefghigkl'; str = str.toUpperCase(); console.log(str); //"ABCDEFGHIGKL"
It converts each character of the given string to uppercase and returns the converted string. It does not changes the original string.
Converting some characters to uppercase
We will loop through each characters of the string and convert only the required characters to uppercase.
let vowels = ['A', 'E', 'I', 'O', 'U']; let str = "LeaRNeRSBuCKeT iS THe BeST WeBSiTe To LeaRN PRoGRaMMiNG"; let temp = ""; for(let chars of str){ if(vowels.includes(chars)){ temp += chars.toUpperCase(); }else{ temp += chars; } } console.log(temp); //"LEARNERSBUCKET IS THE BEST WEBSITE TO LEARN PROGRAMMING"
We have converted all the vowels to the uppercase and return the converted string.
Converting the first character of the string to uppercase
let str = "eXAMPLE"; let temp = str.slice(0,1).toUpperCase() + str.slice(1, str.length); console.log(temp); //EXAMPLE
Learn more about the slice.
Using array to make string uppercase
We will loop through the each character of the string and check the ASCII value of the each character with charCodeAt().
If the character is lowercase alphabet then we will convert it to uppercase with fromCharCode(). Else we will keep the original character.
let str = 'a(b)cdef{1}g2hi3gk%!78l'; let temp = ""; for(let chars of str){ //Get the ascii value of character let value = chars.charCodeAt(); //If the character is in uppercase if(value >= 97 && value <= 122){ //convert it to lowercase temp += String.fromCharCode(value - 32); }else{ //else add the original character temp += chars; } } console.log(temp); //"A(B)CDEF{1}G2HI3GK%!78L"
fromCharCode()
creates a character with the ASCII value and charCodeAt()
returns the ASCII value of the character.