How to convert string to all lower letters in javascript


This is an short tutorial on how to convert an string to lowercase letters in javascript.

For example, if an input is “Welcome to Cloudhadoop” and Output is “welcome to cloudhadoop”

There are multiple ways to convert to lower case string

Inbuilt in toLowerCase() function in javascript

String provides toLowerCase() function to convert to lowercase letters.

Syntax:

toLowerCase()

It returns new string in lowercase letters.

Here is an example

const str = 'Welcome to Cloudhadoop';
const resultStr = str.toLowerCase();
console.log(resultStr); // welcome to cloudhadoop

Convert string in lowercase letters with ascii code

This example is an custom implementation without using toLowercase

  • Read the string chracter by characters and iterate using for loop
  • Find each character ASCII code
  • if character is Upper Case ie upper letter ASCII code is in between 91 and 64.
  • Add 32 to get lowercase ASCII code,
  • Convert ascii to character using fromCharCode
  • append the lower case character to output string
  • Finally, Return output string
const str = 'Welcome to Cloudhadoop';
console.log(" lowerCaseString",  convertToLowerCase(str));

function stringToLowerCase(str) {
  var output = '';

  for (var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code > 64 && code < 91) {
      output += String.fromCharCode(code + 32);
    } else {
      output += str.charAt(i);
    }
  }
  return output;
}

Difference between toLowerCase and toLocalLowerCase

toLowerCase and toLocalLowerCase are returns a string lower case letters, But toLocalLowerCase takes locale language and convert string differently in lower case. to

Conclusion

Converting string in upper case or normal case to lower case is an easy and straightforward.

Tw

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.