TypeScript String trim() Method

The trim() method is an inbuilt method of TypeScript. It is used to eliminate any kind of extra spaces, from the front and end to both sides of the provided string. It’s important to note that this function exists in JavaScript as well.

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: The below code example is a basic implementation of the trim() method in TypeScript.

Javascript




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


Output:

w3wiki

Example 2: In below code the string is defined using the tab and other special space characters, we will remove it using the trim() method.

Javascript




const str: string = "\tHello\n Beginner!\n";
const trimmedStr: string = str.trim();
console.log(trimmedStr);


Output:

Hello
Beginner!

Contact Us