Convert a String to Lowercase in TypeScript

As a TypeScript developer, you might be working with string manipulations. One such example is converting strings to lowercase.

TypeScript provides several methods to convert strings to lowercase.

In this tutorial, I’ll walk you through various methods to convert strings to lowercase in TypeScript, complete with examples and best practices.

Method 1: Using the toLowerCase() Method

The best way to convert a string to lowercase in TypeScript is to use the built-in toLowerCase() method.

Basic Syntax

const originalString: string = "HELLO WORLD";
const lowercaseString: string = originalString.toLowerCase();
console.log(lowercaseString); // Output: "hello world"

The toLowerCase() method creates a new string with all characters converted to lowercase. It doesn’t modify the original string (strings are immutable in JavaScript/TypeScript).

Here is the exact output, as shown in the screenshot.

Python replace multiple characters in a string

Practical Example

Here is an example where I have used the toLowerCase() method to convert a string to lowercase.

function normalizeUserInput(input: string): string {
  return input.toLowerCase();
}

// Usage example
const userEmail: string = "John.Doe@EXAMPLE.com";
const normalizedEmail: string = normalizeUserInput(userEmail);
console.log(normalizedEmail); // Output: "john.doe@example.com"

Check out Remove the Last Character from a String in TypeScript

Method 2: Using TypeScript’s Utility Type – Lowercase

TypeScript 4.1 introduced several intrinsic string manipulation types, including the Lowercase<T> utility type. This type operates at the type level, not at runtime.

Basic Syntax

Here is the syntax:

type LowercaseExample = Lowercase<"HELLO WORLD">;
// Type is: "hello world"

This is a type transformation, which means it affects TypeScript’s static type checking but doesn’t actually transform strings at runtime. It’s useful for type-level operations.

Practical Example

Here is an example.

// Define the types
type EmailDomain = "GMAIL.COM" | "YAHOO.COM" | "OUTLOOK.COM";
type NormalizedEmailDomain = Lowercase<EmailDomain>; 
// Equivalent to: "gmail.com" | "yahoo.com" | "outlook.com"

// Function that uses those types
function sendEmail<T extends string>(address: string, domain: Lowercase<T>) {
  const fullEmail = `${address}@${domain}`;
  console.log(`Sending email to: ${fullEmail}`);
}

// Example usage:
const userAddress = "john.doe";
const domain: NormalizedEmailDomain = "gmail.com";

sendEmail(userAddress, domain);

Here is the exact output in the screenshot below:

How to Convert a String to Lowercase in TypeScript

Check out Remove a Substring from a String in TypeScript

Method 3: Create a Custom Function for Advanced Lowercase Conversion

Now, let me show you how to create a custom function for advanced lowercase conversion.

Basic Implementation

Here is a basic implementation.

function advancedToLowerCase(input: string): string {
  // Apply standard toLowerCase
  let result = input.toLowerCase();

  // Add any custom logic here
  return result;
}

Handle Special Cases

Here is the modified version of the above method that can handle special cases in TypeScript.

function smartCaseConverter(input: string, preserveAcronyms: boolean = false): string {
  if (!preserveAcronyms) {
    return input.toLowerCase();
  }

  // Regex to identify acronyms (all caps words)
  const acronymRegex = /\b[A-Z]{2,}\b/g;
  const acronyms: string[] = input.match(acronymRegex) || [];

  // First convert everything to lowercase
  let result = input.toLowerCase();

  // Then restore acronyms
  acronyms.forEach(acronym => {
    const lowercaseAcronym = acronym.toLowerCase();
    // Replace all occurrences with the original
    result = result.replace(new RegExp(`\\b${lowercaseAcronym}\\b`, 'g'), acronym);
  });

  return result;
}

// Usage
const text = "NASA launched a new SATELLITE into orbit";
console.log(smartCaseConverter(text, true));
// Output: "nasa launched a new SATELLITE into orbit"

Check out Replace Characters in a String Using TypeScript

Method 4: Creating SEO-Friendly Slugs with Lowercase

This method is beneficial if you have a product or are running an e-commerce business. Therefore, give this method careful attention.

When creating URLs for product pages, converting strings to lowercase is a crucial part of the slugification process.

Here is a function and an example.

function createSlug(title: string): string {
  return title
    .toLowerCase()           // Convert to lowercase
    .replace(/\s+/g, '-')    // Replace spaces with hyphens
    .replace(/[^\w\-]+/g, '') // Remove non-word chars
    .replace(/\-\-+/g, '-')   // Replace multiple hyphens with single hyphen
    .replace(/^-+/, '')       // Trim hyphens from start
    .replace(/-+$/, '');      // Trim hyphens from end
}

// Usage
const blogTitle = "How to Convert a String to Lowercase in TypeScript?";
const urlSlug = createSlug(blogTitle);
console.log(urlSlug); // Output: "how-to-convert-a-string-to-lowercase-in-typescript"

Performance Considerations

When working with strings at scale, performance matters. Here’s a comparison of different methods:

MethodPerformanceUse Case
toLowerCase()FastGeneral purpose, most common usage
TypeScript Lowercase<T>N/A (compile-time only)Type-level transformations
Custom functionsVariesComplex scenarios requiring special handling

Handle Non-English Characters

Based on my experience, I can explain some common problems and their solutions. One problem is how to handle non-English characters.

The toLowerCase() method handles most international characters correctly, but be aware of some edge cases. Here is an example.

const germanText = "GROßE"; // German word with eszett (ß)
console.log(germanText.toLowerCase()); // "große"

Check out Check if a String is Null or Empty in TypeScript

Real-World Applications: Implement Search Functionality

Now, let me show you how to implement search functionality and use the toLowerCase() method in TypeScript.

The purpose of this is to search through a list of Product objects and return only the ones that match the search query (case-insensitive).

Parameters:

  • products: an array of Product objects.
  • query: a string that represents what you’re searching for.

Returns: an array of Product objects where the name or description includes the search query.

How it works:

  1. Converts the query to lowercase for case-insensitive matching.
  2. Uses .filter() to go through each product.
  3. Inside .filter(), it checks:
    • If the lowercase name or description includes the lowercase query.
  4. Returns only the matching products.

Here is the complete code:

type Product = {
    name: string;
    description: string;
  };
  function searchProducts(products: Product[], query: string): Product[] {
    const lowercaseQuery = query.toLowerCase();
    return products.filter(product => 
      product.name.toLowerCase().includes(lowercaseQuery) ||
      product.description.toLowerCase().includes(lowercaseQuery)
    );
  }
  const products: Product[] = [
    { name: "Laptop", description: "A powerful machine for work and play" },
    { name: "Phone", description: "Portable device to stay connected" },
    { name: "Tablet", description: "Lightweight device with a touchscreen" },
  ];
  
  const query = "device";
  
  const results = searchProducts(products, query);
  
  console.log(results);

Once you can run the TypeScript code, you can see the output in the screenshot below:

Convert a String to Lowercase in TypeScript

Conclusion

In this tutorial, I explained how to convert strings to lowercase in TypeScript using various methods, such as the toLowerCase() method.

I have also demonstrated how to create a custom function that can handle even special cases. Finally, I have shown a complete real example.

Do let me know if you still have any questions.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.