How to convert string to all lower letters in javascript
- Admin
- Sep 20, 2023
- Javascript
It is a short tutorial on how to convert a string to lowercase letters in javascript.
For example, if the input is “Welcome to Cloudhadoop” and the Output is “welcome to cloudhadoop”. You can check my other post on Javascript check substring exists in a String There are multiple ways to convert to lowercase strings.
Inbuilt in toLowerCase() function in javascript
String provides toLowerCase() function to convert to lowercase letters.
Syntax:
toLowerCase();
It returns a 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 into lowercase letters with ASCII code
This example is a custom implementation without using toLowercase
- Read the string character by character and iterate using for loop
- Find each character’s ASCII code
- if the character is Upper Case i.e upper letter ASCII code is between 91 and 64.
- Add 32 to get lowercase ASCII code,
- Convert ASCII to a character using
fromCharCode
. - append the lowercase character to the output string
- Finally, Return the 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
return a string of lowercase letters, But toLocalLowerCase
takes the locale language and converts the string differently into lowercase.
Conclusion
Converting string from upper case or normal case to lower case is straightforward.