Get and Check String Length in TypeScript

When building a web application using TypeScript, checking the length of user input is a common and important task.

For example, on a user registration form for an e-commerce website, you may want to ensure that the username is at least 5 characters long, the password has a minimum of 8 characters, and the description doesn’t exceed 250 characters.

These simple checks help you display useful error messages to users, reduce mistakes before sending data to the server, and maintain clean and reliable data.

In this tutorial, we will learn how to get and check String length in TypeScript using real-time examples and step-by-step explanations.

String Length in TypeScript

In TypeScript, strings have a built-in length property that returns the number of characters in a string. It’s simple to use and gives you immediate access to the character count.

Here’s the basic syntax:

const myString: string = "Hello, TypeScript!";
const stringLength: number = myString.length;

console.log(stringLength); // Output: 17

When working with the length property, remember that it returns the total number of UTF-16 code units in the string. For most English text and basic symbols, this is the same as the character count.

String Length Method in TypeScript

Check out: Check if an Object is a String in TypeScript

Validate String Length in TypeScript

One of the most common use cases for checking string length is input validation. Let’s look at some practical examples:

1. Checking Minimum String Length in TypeScript

function isValidUsername(username: string): boolean {
  return username.length >= 3;
}

// Usage
const shortName = "ab";
const goodName = "john_doe";

console.log(isValidUsername(shortName)); // false
console.log(isValidUsername(goodName)); // true

Output:

Get and Check String Length in TypeScript

Check Out: Check if a Value Exists in an Enum in TypeScript

2. Checking Maximum String Length in TypeScript

function isValidTweet(tweet: string): boolean {
  return tweet.length <= 280;
}

// Usage
const longTweet = "..."; // Imagine a very long string here
console.log(isValidTweet(longTweet)); // false if > 280 characters

Output:

Check Maximum String Length in TypeScript

3. Checking Range (Min and Max) of String in TypeScript

function isValidPassword(password: string): boolean {
  return password.length >= 8 && password.length <= 20;
}

// Usage
console.log(isValidPassword("pass")); // false (too short)
console.log(isValidPassword("securePassword123")); // true

Output:

Check String Range in TypeScript

Check out: Optional Parameters in TypeScript Interfaces

String Length in Form Validation in TypeScript

When building forms in TypeScript applications, string length validation is essential. Here’s how you might implement it in a real-world scenario:

interface MyFormData {
  firstName: string;
  lastName: string;
  email: string;
  bio: string;
}

interface ValidationErrors {
  firstName?: string;
  lastName?: string;
  email?: string;
  bio?: string;
}

function validateForm(data: MyFormData): ValidationErrors {
  const errors: ValidationErrors = {};

  if (data.firstName.length === 0) {
    errors.firstName = "First name is required";
  } else if (data.firstName.length > 50) {
    errors.firstName = "First name cannot exceed 50 characters";
  }

  if (data.lastName.length === 0) {
    errors.lastName = "Last name is required";
  } else if (data.lastName.length > 50) {
    errors.lastName = "Last name cannot exceed 50 characters";
  }

  if (data.bio.length > 500) {
    errors.bio = "Bio cannot exceed 500 characters";
  }

  return errors;
}

const formData: MyFormData = {
  firstName: "",
  lastName: "Doe",
  email: "[email protected]",
  bio: "Hello there!"
};

const result = validateForm(formData);
console.log("Validation Result:", result);

Output:

String Length in Form Validation in TypeScript

Check out: How to Convert String to Number in TypeScript?

Checking If a String is Empty in TypeScript

Checking if a string is empty is a common task. There are several ways to do this in TypeScript:

1. Using the Length Property in TypeScript

function isEmpty(str: string): boolean {
  return str.length === 0;
}

console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // false (contains a space)

2. Direct Comparison in TypeScript

function isEmpty(str: string): boolean {
  return str === "";
}

3. Checking for Empty or Whitespace in TypeScript

Sometimes you want to consider strings with only whitespace as “empty”:

function isEmptyOrWhitespace(str: string): boolean {
  return str.trim().length === 0;
}

console.log(isEmptyOrWhitespace("")); // true
console.log(isEmptyOrWhitespace(" ")); // true
console.log(isEmptyOrWhitespace("\t\n")); // true
console.log(isEmptyOrWhitespace("hello")); // false

Output:

Check for Empty or Whitespace in TypeScript

Check out: How to Convert a String to Boolean in TypeScript?

String Length and Array Methods in TypeScript

TypeScript’s string methods can be combined with length checks for powerful operations:

1. Truncating a String in TypeScript

function truncate(str: string, maxLength: number): string {
  if (str.length <= maxLength) {
    return str;
  }
  return str.slice(0, maxLength) + "...";
}

const longText = "This is a very long description that needs to be truncated for display purposes.";
console.log(truncate(longText, 20)); // "This is a very long..."

Output:

Truncate a String in TypeScript

2. Padding a String to a Specific Length

function padWithZeros(num: number, targetLength: number): string {
  const numStr = num.toString();

  if (numStr.length >= targetLength) {
    return numStr;
  }

  return "0".repeat(targetLength - numStr.length) + numStr;
}

console.log(padWithZeros(42, 5)); // "00042"

Output:

Padding String to Specific Length in TypeScript

Working with Unicode and Special Characters in TypeScript

When working with international text or special characters, be aware that the length property counts UTF-16 code units, not visible characters:

const emoji = "👨‍👩‍👧‍👦";
console.log(emoji.length); // 11 (not 1)

const heart = "❤️";
console.log(heart.length); // 2 (not 1)

For more accurate character counting with emoji and other complex Unicode characters, you may need specialized libraries or more complex code.

Length of Special Characters in TypeScript

Best Practices for Working with String Length in TypeScript

Based on my experience, here are some best practices:

  1. Be Clear About Requirements: Know exactly what your minimum and maximum lengths should be before implementing validation.
  2. Consider UI Feedback: When validating form inputs, provide real-time feedback about remaining characters.
  3. Handle Edge Cases: Always consider empty strings, whitespace-only strings, and strings with special characters.
  4. Use Type Guards: Leverage TypeScript’s type system to ensure you’re always working with strings:
function getStringLength(input: unknown): number {
  if (typeof input === "string") {
    return input.length;
  }
  return 0; // or throw an error, depending on requirements
}
  1. Test Thoroughly: Validate your length with boundary values (specifically at the minimum and maximum lengths) and edge cases.

Practical Example in TypeScript: Credit Card Formatter

Here’s a practical example that uses string length to format a credit card number as the user types:

function formatCreditCard(input: string): string {
  // Remove all non-digit characters
  const digitsOnly = input.replace(/\D/g, "");

  // Limit to 16 digits
  const limitedDigits = digitsOnly.slice(0, 16);

  // Format with spaces every 4 digits
  let formatted = "";
  for (let i = 0; i < limitedDigits.length; i++) {
    if (i > 0 && i % 4 === 0) {
      formatted += " ";
    }
    formatted += limitedDigits[i];
  }

  return formatted;
}

// Example usage
console.log(formatCreditCard("4111222233334444")); // "4111 2222 3333 4444"
console.log(formatCreditCard("4111-2222-3333-4444")); // "4111 2222 3333 4444"

This function uses string length to ensure we only accept 16 digits and to determine where to insert spaces.

Credit Card Formatter in TypeScript

Conclusion

Working with string lengths in TypeScript is straightforward but powerful. Whether you’re validating user input, formatting text for display, or implementing complex string operations, the length property gives you the information you need.

Remember that while the basic concepts are simple, real-world applications often require careful consideration of edge cases, internationalization concerns, and user experience factors.

I hope you found this guide helpful for your TypeScript projects. If you have any questions or suggestions, feel free to leave them in the comments below.

Other TypeScript articles 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.