TypeScript String trim()

In this chapter, we will explore the trim() method in TypeScript. This method is a built-in function that helps in removing whitespace from both ends of a string. Understanding how to use trim() is useful for cleaning up strings, especially when processing user input or formatting data.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The trim() method removes whitespace from both ends of a string and returns a new string. Whitespace in this context includes spaces, tabs, and newline characters.

2. Syntax

string.trim();

Parameters

The trim() method does not take any parameters.

Return Value

The method returns a new string representing the calling string with whitespace removed from both ends.

3. Examples

Let's look at some examples to understand how trim() works in TypeScript.

Example 1: Basic Usage

In this example, we remove whitespace from both ends of a string.

let str: string = "   Hello, TypeScript!   ";
let result = str.trim();
console.log(result); // Output: "Hello, TypeScript!"

Example 2: String with No Whitespace

In this example, we use trim() on a string that has no leading or trailing whitespace.

let str: string = "Hello, TypeScript!";
let result = str.trim();
console.log(result); // Output: "Hello, TypeScript!"

Example 3: String with Tabs and Newlines

In this example, we use trim() on a string that contains tabs and newline characters.

let str: string = "\t\n  Hello, TypeScript!  \n\t";
let result = str.trim();
console.log(result); // Output: "Hello, TypeScript!"

Example 4: Multiple Whitespace Characters

In this example, we use trim() on a string with multiple whitespace characters at both ends.

let str: string = "    Hello, TypeScript!    ";
let result = str.trim();
console.log(result); // Output: "Hello, TypeScript!"

Example 5: Using trim() for User Input

In this example, we use trim() to clean up user input by removing any extraneous whitespace.

let userInput: string = "   John Doe   ";
let cleanedInput = userInput.trim();
console.log(`User input: '${cleanedInput}'`); // Output: "User input: 'John Doe'"

4. Conclusion

In this chapter, we explored the trim() method in TypeScript, which is used to remove whitespace from both ends of a string. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use trim() effectively can help in various string manipulation tasks in TypeScript, especially when cleaning up strings and processing user input.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare