Quick Tip: How to Transform the Character Case of a String in JavaScript

Share this article

How to Transform the Character Case of a String in JavaScript

In this tutorial, you’ll learn how to transform the character case of a string — to uppercase, lowercase, and title case — using native JavaScript methods.

JavaScript provides many functions and methods that allow you to manipulate data for different purposes. We’ve recently looked at methods for converting a string to a number and a number to a string or to an ordinal, and for splitting strings. This article will present methods for transforming the character case of a string — which is useful for representing strings in a certain format or for reliable string comparison.

Transform a String to Lowercase

If you need your string in lowercase, you can use the toLowerCase() method available on strings. This method returns the string with all its characters in lowercase.

For example:

const str = 'HeLlO';
console.log(str.toLowerCase()); // "hello"
console.log(str); // "HeLlo"

By using toLowerCase() method on the str variable, you can retrieve the same string with all the characters in lowercase. Notice that a new string is returned without affecting the value of str.

Transform a String to Uppercase

If you need your string in uppercase, you can use the toUpperCase() method available on strings. This method returns the string with all its characters in uppercase.

For example:

const str = 'HeLlO';
console.log(str.toUpperCase()); // "HELLO"
console.log(str); // "HeLlo"

By using toUpperCase() method on the str variable, you can retrieve the same string with all the characters in uppercase. Notice that a new string is returned without affecting the value of str.

Transform a String to Title Case

The most common use case for transforming a string’s case is transforming it to title case. This can be used to display names and headlines.

There are different ways to do this. One way is by using the method toUpperCase() on the first character of the string, then concatenating it to the rest of the string. For example:

const str = 'hello';
console.log(str[0].toUpperCase() + str.substring(1).toLowerCase()); // "Hello"

In this example, you retrieve the first character using the 0 index on the str variable. Then, you transform it to uppercase using the toUpperCase() method. Finally, you retrieve the rest of the string using the substr() method and concatinate the rest of the string to the first letter. You apply toLowerCase() on the rest of the string to ensure that it’s in lowercase.

This only transforms the first letter of the word to uppercase. However, in some cases if you have a sentence you might want to transform every word in the sentence to uppercase. In that case, it’s better to use a function like this:

function toTitleCase (str) {
  if (!str) {
    return '';
  }
  const strArr = str.split(' ').map((word) => {
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  });
  return strArr.join(' ');
}

const str = 'hello world';
console.log(toTitleCase(str)); // "Hello World"

The toTitleCase() function accepts one parameter, which is the string to transform to title case.

In the function, you first check if the string is empty and in that case return an empty string.

Then, you split the string on the space delimiter, which returns an array. After that, you use the map method on the array to apply the transformation you saw in the previous example on each item in the array. This transforms every word to title case.

Finally, you join the items in the array into a string by the same space delimiter and return it.

Live Example

In the following CodePen demo, you can try out the functionality of toLowerCase() and toUpperCase(). When you enter a string in the input, it’s transformed to both uppercase and lowercase and displayed. You can try using characters with different case in the string.

See the Pen Transform the Character Case of a String in JavaScript by SitePoint (@SitePoint) on CodePen.

Changing Character Case for String Comparison

In many situations, you’ll need to compare strings before executing a block of code. If you can’t control the character case the string is being written in, performing comparison on the string without enforcing any character case can lead to unexpected results.

For example:

const input = document.querySelector('input[type=text]');
if (input.value === 'yes') {
  alert('Thank you for agreeing!');
} else {
  alert('We still like you anyway')
}

If the user enters in the input Yes instead of yes, the equality condition will fail and the wrong alert will show.

You can resolve this by enforcing a character case on the string:

const input = document.querySelector('input[type=text]');
if (input.value.toLowerCase() === 'yes') {
  alert('Thank you for agreeing!');
} else {
  alert('We still like you anyway')
}

Conclusion

It’s necessary to learn how to transform the character case of a string in JavaScript. You’ll often need to use it for many use cases, such as displaying the string in a certain format. You can also use it to reliably compare strings.

Enforcing a character case on the strings you’re comparing ensures that you can check if the content of the strings are equal, regardless of how they’re written.

If you found this article useful, you may also enjoy the following:

Frequently Asked Questions (FAQs) about JavaScript String Transformation

What is the difference between toUpperCase() and toLowerCase() in JavaScript?

In JavaScript, toUpperCase() and toLowerCase() are two methods used to transform the case of a string. The toUpperCase() method converts all the characters in a string to uppercase letters. On the other hand, the toLowerCase() method converts all the characters in a string to lowercase letters. These methods do not change the original string but return a new string with the transformed case.

Can I use toUpperCase() and toLowerCase() methods with non-English characters?

Yes, the toUpperCase() and toLowerCase() methods in JavaScript work with non-English characters as well. These methods are Unicode-aware, so they can handle strings containing special characters, symbols, and characters from different languages. However, the behavior might be different for some languages due to specific language rules for case conversion.

How can I convert only the first letter of a string to uppercase in JavaScript?

To convert only the first letter of a string to uppercase in JavaScript, you can use the charAt() method in combination with the toUpperCase() method. Here’s how you can do it:

let str = "hello";
let result = str.charAt(0).toUpperCase() + str.slice(1);

In this code, charAt(0) gets the first character of the string, toUpperCase() converts it to uppercase, and slice(1) gets the rest of the string.

What happens if I use toUpperCase() or toLowerCase() on a number or a boolean?

If you use toUpperCase() or toLowerCase() on a number or a boolean, JavaScript will first convert the number or boolean to a string and then apply the case transformation. For example, (123).toString().toUpperCase() will return “123”, and (true).toString().toUpperCase() will return “TRUE”.

Can I use toUpperCase() and toLowerCase() methods on an array of strings?

Yes, you can use the toUpperCase() and toLowerCase() methods on an array of strings in JavaScript. However, you need to use the map() function to apply these methods to each element of the array. Here’s an example:

let arr = ["hello", "world"];
let uppercasedArr = arr.map(str => str.toUpperCase());

In this code, map() applies the toUpperCase() method to each string in the array, resulting in an array of uppercase strings.

Are there any performance differences between toUpperCase() and toLowerCase()?

In general, the performance of toUpperCase() and toLowerCase() methods in JavaScript is very similar. Both methods have a time complexity of O(n), where n is the length of the string. Therefore, the performance difference between these methods is negligible for most applications.

How can I check if a string is in uppercase or lowercase in JavaScript?

To check if a string is in uppercase or lowercase in JavaScript, you can compare the original string with its uppercased or lowercased version. If the original string is equal to its uppercased version, then the string is in uppercase. Similarly, if the original string is equal to its lowercased version, then the string is in lowercase.

Can I use toUpperCase() and toLowerCase() methods in Node.js?

Yes, the toUpperCase() and toLowerCase() methods are part of the JavaScript language, so you can use them in Node.js as well. These methods are available on all string objects in Node.js.

Are there any alternatives to toUpperCase() and toLowerCase() in JavaScript?

In JavaScript, toUpperCase() and toLowerCase() are the standard methods for transforming the case of a string. However, you can also use CSS to transform the case of a string for display purposes. The text-transform property in CSS can be used to change the case of text in HTML elements.

How can I convert a string to title case in JavaScript?

JavaScript does not have a built-in method for converting a string to title case. However, you can create a custom function to do this. Here’s an example:

function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}

In this function, the replace() method with a regular expression is used to match each word in the string, and then the first character of each word is converted to uppercase and the rest to lowercase.

Dianne PenaDianne Pena
View Author

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

JS Quick Tipsstrings
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week