Mastering Case Transformations in JavaScript

February, 25th 2025 1 min read

How to Convert a String to Lowercase and Uppercase in JavaScript

String case conversion is a fundamental operation in JavaScript. While simple methods exist, we can explore more complex, creative, and performance-optimized ways to handle case transformation. This article covers multiple techniques, including built-in methods, ASCII manipulation, regex-based approaches, and even WebAssembly for extreme performance.

1. Using Built-In Methods

Lowercase Conversion

js
const str = 'Hello World!';
const lower = str.toLowerCase();
console.log(lower); // Output: hello world!

Uppercase Conversion

js
const upper = str.toUpperCase();
console.log(upper); // Output: HELLO WORLD!

2. ASCII-Based Conversion (Manual Transformation)

js
function toLowerCaseASCII(str) {
  return str
    .split('')
    .map(char => {
      let code = char.charCodeAt(0);
      return code >= 65 && code <= 90 ? String.fromCharCode(code + 32) : char;
    })
    .join('');
}

function toUpperCaseASCII(str) {
  return str
    .split('')
    .map(char => {
      let code = char.charCodeAt(0);
      return code >= 97 && code <= 122 ? String.fromCharCode(code - 32) : char;
    })
    .join('');
}

3. Using Regular Expressions

js
function toLowerCaseRegex(str) {
  return str.replace(/[A-Z]/g, letter =>
    String.fromCharCode(letter.charCodeAt(0) + 32)
  );
}

function toUpperCaseRegex(str) {
  return str.replace(/[a-z]/g, letter =>
    String.fromCharCode(letter.charCodeAt(0) - 32)
  );
}

4. Using WebAssembly (WASM)

c
#include <emscripten.h>
#include <string.h>
...

Conclusion

JavaScript provides multiple ways to convert string cases, from simple methods like built-in methods to advanced techniques involving ASCII manipulation, regex, and WebAssembly.