The toLowerCase in JavaScript is a method useful for converting a string to lowercase and has the following syntax:

string.toLowerCase();

Where string represents the string to convert to lowercase.

Also in this case, as with the toUpperCase method, seen in the previous lesson, the original string is not changed. So to see the result we have to use a variable where to save the converted string, it can also be the variable itself.

toLowerCase JavaScript – first example

We transform an input string with lowercase characters.

Here is the proposed example that uses the JavaScript toLowerCase method:



var string = 'CODing';
if (string == string.toLowerCase()){
   document.write('The string is already lowercase' + coding);
} else {
  string = string.toLowerCase();
  document.write('The transformed string is: ' + stringa);
}

With the conditional statement we evaluate if the starting string is already lowercase and in this case we print it without converting it. Otherwise we convert the string and print it.

Of course we could directly convert it, regardless of whether it was lowercase.

toLowerCase JavaScript – second example

In this second example we use the getElementById method explained in this tutorial: getElementById method.

We take a value from a prompt and turn it to lowercase. After we display it in an html section with id result.

Here is the code necessary for the realization of the proposed example that uses the JavaScript toLowerCase method.



var name = prompt('Insert the name');
name = name.toLowerCase();
document.getElementById("result")
  .innerHTML ="The name is: " + name;

So here is the example html code:

<h1>Example with the toLowerCase and getElementById method</h1>
<label>Insert the name: </label>
<p id="result"></p>

In this example we convert the name directly to uppercase without checking that it already is. Eventually, as in the previous exercise, we could decide to do it always using conditional statements.

Banner pubblicitario

Conclusion

In this lesson we studied the JavaScript toLowerCase method for transforming input strings to lowercase. In the next few lessons we will see many more examples that use other methods on strings in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript