Convert a string to lowercase in javascript

Learn how to convert a string to lowercase in javascript.

There are situations some times where you want to convert the single, multiple or each character of the string to lowercase. We will see different ways in which we can achieve the same in javascript.

Using string’s toLowerCase() method.

It only converts the alphabets. Numeric and special characters are untouched.

let str = 'ABCDEFGHIGKL';
str = str.toLowerCase();
console.log(str);
//"abcdefghigkl" 

Javascript toLowerCase() method converts each character of the string to the lowercase and returns the converted string. It does not manipulate the original string.

Converting some characters of the string to lowercase.

We will loop through all the characters of the string and convert only the required characters to the lowercase.

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.toLowerCase();
   }else{
       temp += chars;
   }
}

console.log(temp);
//"LeaRNeRSBuCKeT iS THe BeST WeBSiTe To LeaRN PRoGRaMMiNG"

We have converted all the vowels to the lowercase and created a new string.

Converting first character to lowercase.

let str = "EXAMPLE";
let temp = str.slice(0,1).toLowerCase() + str.slice(1, str.length);
console.log(temp);
//eXAMPLE

Learn more about the slice.


Using Array to make string lowercase.

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 uppercase alphabet then we will convert it to lowercase 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 >= 65 && value <= 90){
    //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.

Leave a Reply

Your email address will not be published. Required fields are marked *