Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert mixed case string to lower case in JavaScript
In JavaScript, there are multiple ways to convert a mixed-case string to lowercase. The most common approach is using the built-in toLowerCase() method, but you can also implement a custom solution using character codes.
Using the Built-in toLowerCase() Method
The simplest and most efficient way is to use JavaScript's built-in toLowerCase() method:
const str = 'ABcD123'; const output = str.toLowerCase(); console.log(output);
abcd123
Custom Implementation Using Character Codes
For educational purposes, here's how to implement a custom convertToLower() function that converts uppercase letters (ASCII 65-90) to lowercase by adding 32 to their character codes:
const str = 'ABcD123';
String.prototype.convertToLower = function(){
let res = '';
for(let i = 0; i < this.length; i++){
const el = this[i];
const code = el.charCodeAt(0);
if(code >= 65 && code <= 90){
res += String.fromCharCode(code + 32);
}else{
res += el;
};
};
return res;
};
console.log(str.convertToLower());
abcd123
How the Custom Method Works
The custom implementation works by:
- Iterating through each character in the string
- Getting the ASCII code using
charCodeAt(0) - Checking if the code is between 65-90 (uppercase A-Z)
- Adding 32 to convert uppercase to lowercase (A=65 becomes a=97)
- Keeping other characters unchanged
Comparison
| Method | Performance | Unicode Support | Recommended |
|---|---|---|---|
toLowerCase() |
Fast | Full Unicode | Yes |
| Custom ASCII method | Slower | ASCII only | Educational only |
Additional Examples
// Different test cases
const examples = ['Hello World!', 'MiXeD123CaSe', 'UPPERCASE', 'lowercase'];
examples.forEach(str => {
console.log(`"${str}" ? "${str.toLowerCase()}"`);
});
"Hello World!" ? "hello world!" "MiXeD123CaSe" ? "mixed123case" "UPPERCASE" ? "uppercase" "lowercase" ? "lowercase"
Conclusion
Use the built-in toLowerCase() method for production code as it handles Unicode characters properly and performs better. The custom implementation is useful for understanding how character conversion works at a lower level.
