Technology News

Quick Tip: 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()); console.log(str); 

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()); console.log(str); 

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()); 

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)); 

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:

Cookie pop-ups have taken over the internet. Here’s how to stop them.
What Is the Best Font for a Flyer?

Related Articles

9 Best Free CSS Flexbox Tutorials

9-best-free-css-flexbox-tutorials
Every modern website needs to be mobile friendly. You can accomplish this by using responsive techniques, one of which is the CSS flexbox feature. Flexbox lets you define layout elements…

Checkout is the key to frictionless B2B e-commerce

checkout-is-the-key-to-frictionless-b2b-e-commerce
Andrew Steele Contributor Andrew Steele is an investor at Activant Capital. He focuses on fintech and e-commerce infrastructure and is based in New York. COVID-19 cemented e-commerce into everyone’s daily…

Zero-Width Space

zero-width-space
The name zero-width space is antithetical, but it’s not without uses. In text, maybe you’d use it around slashes because you want to be sure the words are treated individually…

To Stop AI-Powered Adversaries, Defenders Must Fight Fire with Fire

Exploring the Potential of the Metaverse: A New World Awaits
Anthropic’s Threat Intelligence team recently uncovered and disrupted a sophisticated nation-state operation that weaponized Claude’s agentic capabilities and the Model Context Protocol (MCP) to orchestrate automated cyberattacks simultaneously against multiple…

OKRs: A Complete Guide for Success

OKRs: A Complete Guide for Success
Every organization that wants to grow should have a tried-and-true method of setting goals. There are a few different frameworks to choose from, but which one is right for your…