Saturday, September 23, 2023
HomeProgrammingChanging String to Lowercase in JavaScript

Changing String to Lowercase in JavaScript


Introduction

Should you’ve ever discovered your self needing to standardize consumer enter or put together textual content knowledge for evaluation, then you’ll have wanted to lowercase strings. Whereas there may be one extensively used methodology, there are additionally different string manipulation strategies that it’s best to think about as effectively, which is what we’ll cowl on this Byte.

The Want for Lowercase Conversion

Ever questioned why you’d must convert strings to lowercase? Effectively, let’s think about a situation. Suppose you are constructing a search characteristic for a web site. To make sure that the search is case insensitive, you would want to transform each the search enter and the info being searched right into a uniform case. Lowercase is commonly the go-to selection.

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

JavaScript Strategies for Lowercase Conversion

JavaScript supplies two helpful strategies for changing strings to lowercase: toLowerCase() and toLocaleLowerCase(). These strategies make changing strings to lowercase straightforward to do.

The toLowerCase() Methodology

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

This is a easy instance:

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

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

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

The toLocaleLowerCase() Methodology

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

For example, in Turkish, the uppercase of ‘i’ is ‘Ä°’ (dotted i), not ‘I’. Let’s have a look at 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() methodology accurately converts the ‘Ä°’ to ‘i̇’, respecting the Turkish language guidelines.

Word: 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() methodology. This methodology does not require any parameters and returns a brand new string the place all the unique characters are transformed to lowercase.

let greeting = "Good day, World!";
let lowerCaseGreeting = greeting.toLowerCase();
console.log(lowerCaseGreeting);  // "whats up, world!"

Now, let’s strive utilizing toLocaleLowerCase(). This methodology is just like toLowerCase(), but it surely 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 possibly can see, even the Turkish-specific characters are accurately transformed to lowercase.

Word: The toLocaleLowerCase() methodology 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 state of affairs the place the string you are attempting to transform to lowercase is null or undefined. Let’s have a look at what would occur in such a case.

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

As anticipated, this throws a TypeError. To deal with this, we are able to add a examine to make sure that the string shouldn’t 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 doable difficulty is attempting to transform a non-string knowledge kind to lowercase. For example, when you attempt to convert a quantity to lowercase, you will get a TypeError.

let quantity = 12345;
let lowerCaseNumber = quantity.toLowerCase();
// Uncaught TypeError: quantity.toLowerCase shouldn't be a operate

To deal with this, you would first convert the non-string knowledge kind to a string utilizing the toString() methodology, 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 shouldn’t be the one use-case. One other risk 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() Methodology

So, how can we go about creating and utilizing a technique like this? This methodology 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 = operate() {
    return this.substitute(/wS*/g, operate(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
};

console.log("whats up world".toTitleCase()); // Output: "Good day World"

On this code snippet, we use the substitute() methodology 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() Methodology

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

This is how you would implement it:

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

console.log("whats up world".toProperCase()); // Output: "Good day 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 convert strings to lowercase in JavaScript utilizing the toLowerCase() and toLocaleLowerCase() strategies. We additionally realized create customized strategies like toTitleCase() and toProperCase(). We mentioned potential points you would possibly encounter and deal with them.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments