How to convert string to uppercase lowercase using JavaScript is a common question that you encounter in any JavaScript interviews.

In this tutorial, you’ll learn about two method to convert string to uppercase lowercase using JavaScript.

Convert String To UpperCase LowerCase Using JavaScript

Method 1 : Using ASCII Code

Upper case letters A-Z have ASCII code 65-90. Lower case letters a-z have ASCII code 97-122. You can use the ASCII code to convert the case of the string. Here is a method to convert string to Uppercase using ASCII in JavaScript.

function convertUpperCase(str) {
  let arr = str.split('');
  let output = [];
  let temp;
  for(let i = 0; i < arr.length; i++) {
    if(arr[i].charCodeAt(0) >= 97 && arr[i].charCodeAt(0) <= 122) {
      temp = String.fromCharCode((arr[i].charCodeAt(0) - 32))
      output.push(temp)
    } else {
      output.push(arr[i])
    }
  }
  return output.join('')
}

console.log(convertUpperCase('Hello'))

As seen in the above code, you converted the passed in string to an array. You check for each letter if its in lower case ASCII code range 97-122. If its in lowercase, you convert it to uppercase ASCII by deducting 32.

Similarly, you can write a method to convert string to lowercase using JavaScript based on ASCII code. Here is how it looks :

function convertLowerCase(str) {
  let arr = str.split('');
  let output = [];
  let temp;
  for(let i = 0; i < arr.length; i++) {
    if(arr[i].charCodeAt(0) >= 65 && arr[i].charCodeAt(0) <= 90) {
      temp = String.fromCharCode((arr[i].charCodeAt(0) + 32))
      output.push(temp)
    } else {
      output.push(arr[i])
    }
  }
  return output.join('')
}

console.log(convertLowerCase('Hello'))

Method 2 : Using Built in Method

JavaScript has a built in method which makes it easier to convert string from one case to another. Let’s have a look at an example to see how it works ;

function convertToUpper(input) {
  return input.toUpperCase()
}

function convertToLower(input) {
  return input.toLowerCase(input)
}

console.log(convertToUpper('hello'));
console.log(convertToLower('GOOD'));

The built in methods toUpperCase and toLowerCase converts the string to upper and lower case respectively.