Use JavaScript programming to lowercase a string or a character.

As you know there is no difference between a character and a String in JavaScript language. They both are treated like strings whether a single character or a group of characters as words. The type is always String.

In other programming languages such as C,C++ and Java. A single character and a String is different from one another. Here is a good read that might intrest you Java vs JavaScript.

In this JavaScript tutorial, we will see two ways to change/convert a string to lowercase using an inbuilt function and without an inbuilt function.

Change to Lowercase using the inbuilt function in JavaScript (Recommended)

You can change the string to lowercase using a simple inbuilt function i.e toLowerCase().

That is to say, This is the easiest and a straightforward way to change string to lowercase in JavaScript. The function is used with a dot(.) operator with the string.
Note: No parameter is required and space is ignored in between words.

Below is a JS code example to change string to lowercase –


let string = "THIS IS A STRING";
let result = string.toLowerCase();
console.log(result);

let char = 'A';
result = char.toLowerCase();
console.log(result);

Without using toLowerCase function

Yes, you can change a string without using toLowerCase() function. That is true but this is not recommended as it increases complexity.

The idea behind this is to get the ASCII value and add 32 to it and then convert it back to a string.

 The difference in unicode value of a lowercase and uppercase is 32 for any given set.

Changing a single character of a string from uppercase to lowercase is relatively easy.


let char='A';

let result=char.charCodeAt(0);
result+=32;

result=String.fromCharCode(result);
console.log(result);

Changing a specific character of a string to lowercase is much more complex as we need to use a loop to iterate.


let myString='LETSTACLE TEAM';
let ascii;
let result='';
for(let i=0;i<myString.length;i++){
  if(myString[i]==' ')
    ascii=myString.charCodeAt(i);
  else
    ascii=myString.charCodeAt(i)+32;

  result+=String.fromCharCode(ascii);
}

console.log(result);

The above way is simply to demonstrate the conversion of a string from uppercase to lowercase and how it actually works under the hood. i.e without the use of toLowerCase() function.

As result, understanding the importance of  ASCII value and how it can be used as a medium of conversion is really interesting. Thus, every character is associated with an ASCII / Unicode value only.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed