Convert to Lowercase or Uppercase in JavaScript
Converting to lowercase and uppercase is a common task in JavaScript. This could be for preparing strings for case insensitive searches or for storing normalised values. The good news is modern versions of JavaScript have built-in methods to make case conversion easy and clean.
In this tutorial, we will learn how to convert the case of all the characters and substrings in a JavaScript string up or down.
Convert to Uppercase
To convert all the characters in a string in JavaScript to uppercase we can use the toUpperCase()
method. This method will create a new string from the original string which we can store in a variable.
var string = 'this is some text';
var result = string.toUpperCase();
console.log(result);
THIS IS SOME TEXT
Convert to Lowercase
To convert all characters to uppercase use the toLowerCase()
method. Like to toUpperCase()
, toLowerCase()
will return a new string that could be used immediately or stored in a variable for later use.
var string = 'tHis iS sOme tExt';
var result = string.toLowerCase();
console.log(result);
this is some text
Make the First Character Uppercase
Like many other programming languages, a string is an iterable with each element having an index, the first element is at index 0
. With that in mind, to change the first character to uppercase we just have to modify the first index of the string and replace it with an uppercase character. There are a number of ways to approach this but the probably the easiest is by using the charAt()
and slice()
methods and combining the result.
var string = 'this is some text';
var result = string.charAt(0).toUpperCase() + string.slice(1);;
console.log(result);
This is some text
Convert a Substring to Uppercase or Lowercase
Sometime you may need to make substrings upper or lower case. One way of achieving this in JavaScript is to use the replace()
method and changing the case of the matches before they are added back into the string.
var string = 'this is some text';
var result = string.replace('some', r => r.toUpperCase());
console.log(result);
this is SOME text
In the above example, we are looking for the substring “some” and capitalising it. This is a basic example, which could be expanded on with more elaborate regular expressions for dynamic substring matching.
Conclusion
You now know several different ways to change the casing of characters in a JavaScript string, which can be applied in your own programs.