How can I convert a string to lowercase or uppercase in JavaScript without using toLowerCase() or toUpperCase()?
Benjamin C
benjamin c profile pic

To convert a string to lowercase or uppercase in JavaScript without using the built-intoLowerCase() ortoUpperCase() methods, you can utilize the ASCII character codes and String.fromCharCode() method. Here's a step-by-step approach for each conversion: Converting to lowercase: 1. Initialize an empty string to store the converted lowercase string. 2. Iterate through each character in the input string. 3. Check if the character's ASCII code is within the range of uppercase letters (65-90). 4. If true, add 32 to the character's ASCII code to convert it to lowercase. 5. UseString.fromCharCode() to convert the modified ASCII code back to a character and append it to the result string. 6. After iterating through all the characters, the result string will contain the lowercase version of the input string. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function toLowerCase(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    if (charCode >= 65 && charCode <= 90) {
      const lowerCaseCharCode = charCode + 32;
      result += String.fromCharCode(lowerCaseCharCode);
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

const input = "Hello World";
const lowerCaseString = toLowerCase(input);
console.log(lowerCaseString); // Output: hello world

Converting to uppercase: 1. Follow the same steps as for converting to lowercase, but this time check if the character's ASCII code is within the range of lowercase letters (97-122). 2. If true, subtract 32 from the character's ASCII code to convert it to uppercase. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function toUpperCase(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    if (charCode >= 97 && charCode <= 122) {
      const upperCaseCharCode = charCode - 32;
      result += String.fromCharCode(upperCaseCharCode);
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

const input = "Hello World";
const upperCaseString = toUpperCase(input);
console.log(upperCaseString); // Output: HELLO WORLD

By manually manipulating the character codes using ASCII values, you can achieve the lowercase and uppercase conversions without relying on the built-in methods.