Tuesday, April 2, 2024

Changing String to Lowercase in JavaScript

Must read


Introduction

Should you’ve ever discovered your self needing to standardize consumer enter or put together textual content information for evaluation, then you might have wanted to lowercase strings. Whereas there may be one broadly used technique, there are additionally different string manipulation strategies that you must take into account as effectively, which is what we’ll cowl on this Byte.

The Want for Lowercase Conversion

Ever questioned why you’d have to convert strings to lowercase? Properly, let’s take into account a situation. Suppose you are constructing a search function for a web site. To make sure that the search is case insensitive, you would want to transform each the search enter and the information being searched right into a uniform case. Lowercase is commonly the go-to alternative.

One other widespread use case is information preprocessing in Pure Language Processing (NLP). Earlier than analyzing textual content information, it is usually transformed to lowercase for extra uniformity.

JavaScript Strategies for Lowercase Conversion

JavaScript offers two useful strategies for changing strings to lowercase: toLowerCase() and toLocaleLowerCase(). These strategies make changing strings to lowercase simple to do.

The toLowerCase() Technique

The toLowerCase() technique in JavaScript converts all of the uppercase characters in a string to lowercase characters and returns the consequence. The unique string stays unchanged as this technique returns a brand new string.

This is a easy instance:

let str = "Hey, World!";
let lowerCaseStr = str.toLowerCase();

console.log(lowerCaseStr);  // "hiya, world!"

On this instance, toLowerCase() is named on the string str, changing all uppercase characters to lowercase. The result’s then logged to the console.

The toLocaleLowerCase() Technique

The toLocaleLowerCase() technique, however, considers locale-specific guidelines when changing strings to lowercase. This technique is especially helpful when coping with languages which have locale-specific casing guidelines.

As an illustration, in Turkish, the uppercase of ‘i’ is ‘Ä°’ (dotted i), not ‘I’. Let’s examine this in motion:

let str = "Ä°stanbul";
let lowerCaseStr = str.toLocaleLowerCase('tr-TR');

console.log(lowerCaseStr);  // "i̇stanbul"

On this instance, we’re changing a Turkish phrase to lowercase. The toLocaleLowerCase() technique appropriately converts the ‘Ä°’ to ‘i̇’, respecting the Turkish language guidelines.

Observe: Should you’re coping with English textual content or languages with out particular casing guidelines, toLowerCase() and toLocaleLowerCase() will give the identical outcomes. Nonetheless, for languages with particular casing guidelines, it is best to make use of toLocaleLowerCase().

Extra Examples of Lowercase Conversion

Let’s begin by changing a easy string to lowercase utilizing the toLowerCase() technique. This technique does not require any parameters and returns a brand new string the place all the unique characters are transformed to lowercase.

let greeting = "Hey, World!";
let lowerCaseGreeting = greeting.toLowerCase();
console.log(lowerCaseGreeting);  // "hiya, world!"

Now, let’s strive utilizing toLocaleLowerCase(). This technique is just like toLowerCase(), however it considers the host’s present locale. For many languages, it behaves the identical as toLowerCase().

let greetingInTurkish = "MERHABA, DÃœNYA!";
let lowerCaseGreetingInTurkish = greetingInTurkish.toLocaleLowerCase('tr-TR');
console.log(lowerCaseGreetingInTurkish);  // "merhaba, dünya!"

As you may see, even the Turkish-specific characters are appropriately transformed to lowercase.

Observe: The toLocaleLowerCase() technique takes a locale argument. If no locale is offered, it makes use of the host’s present locale.

Potential Points and Options

Coping with Null or Undefined

Whereas working with JavaScript, you would possibly encounter a scenario the place the string you are attempting to transform to lowercase is null or undefined. Let’s examine what would occur in such a case.

let nullString = null;
let lowerCaseNullString = nullString.toLowerCase();
// Uncaught TypeError: Can not learn property 'toLowerCase' of null

As anticipated, this throws a TypeError. To deal with this, we are able to add a test to make sure that the string will not be null or undefined earlier than we attempt to convert it to lowercase.

let nullString = null;
let lowerCaseNullString = nullString ? nullString.toLowerCase() : null;
console.log(lowerCaseNullString);  // null

Dealing with Non-String Knowledge Varieties

One other potential subject is attempting to transform a non-string information kind to lowercase. As an illustration, in case you attempt to convert a quantity to lowercase, you will get a TypeError.

let quantity = 12345;
let lowerCaseNumber = quantity.toLowerCase();
// Uncaught TypeError: quantity.toLowerCase will not be a perform

To deal with this, you can first convert the non-string information kind to a string utilizing the toString() technique, after which convert it to lowercase.

let quantity = 12345;
let lowerCaseNumber = quantity.toString().toLowerCase();
console.log(lowerCaseNumber);  // "12345"

Different Case Conversions

Changing all letters to lowercase will not be the one use-case. One other chance is to transform some, however not all, letters to lowercase whereas both leaving others alone or changing them to uppercase. Each toTitleCase() and toProperCase() do that.

Whereas strategies like these are usually not inherently supported by JavaScript, we are able to both write these strategies ourselves or use utility libraries like Lodash that do present them.

The toTitleCase() Technique

So, how will we go about creating and utilizing a technique like this? This technique will convert the primary character of every phrase in a string to uppercase, whereas the remainder of the characters stay in lowercase.

This is a easy implementation:

String.prototype.toTitleCase = perform() {
    return this.change(/wS*/g, perform(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
};

console.log("hiya world".toTitleCase()); // Output: "Hey World"

On this code snippet, we use the change() technique with a daily expression to match every phrase within the string. For every matched phrase, we convert the primary character to uppercase and the remainder to lowercase.

The toProperCase() Technique

One other technique that JavaScript doesn’t assist natively is toProperCase(). This technique is just like toTitleCase(), however it solely capitalizes the primary letter of the string, leaving the remainder of the string in lowercase.

This is how you can implement it:

String.prototype.toProperCase = perform() {
    return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
};

console.log("hiya world".toProperCase()); // Output: "Hey world"

On this code, we’re utilizing charAt(0).toUpperCase() to transform the primary character of the string to uppercase. Then, we use slice(1).toLowerCase() to transform the remainder of the string to lowercase.

Conclusion

On this Byte, we have explored the best way to convert strings to lowercase in JavaScript utilizing the toLowerCase() and toLocaleLowerCase() strategies. We additionally discovered the best way to create customized strategies like toTitleCase() and toProperCase(). We mentioned potential points you would possibly encounter and the best way to deal with them.



Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article