Open In App

TypeScript String trim() Method

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The TypeScript String trim() method is used to remove whitespace from both sides of a string. This method is also available in JavaScript because it is a subset of TypeScript. It returns a new string without leading or trailing spaces

Syntax

string.trim()

Parameters:

This method does not take any parameters.

Return Value:

It returns a new string that has been stripped of any leading or trailing whitespace.

Example 1: Basic Implementation String trim() Method

In this example we declares a string str with leading and trailing spaces. The trim() method removes these spaces.

TypeScript
const str: string = " GeeksforGeeks ";
const trimmedStr: string = str.trim();
console.log(trimmedStr);

Output:

GeeksforGeeks

Example 2: Removing Special Whitespace Characters

In this example we defines a string with tabs and newlines. The trim() method removes all leading and trailing whitespace.

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

Output:

Hello Geeks!

Next Article

Similar Reads