Javascript String Trim Method (with Example)

In this tutorial, you will learn about the javascript string trim() method with the help of multiple examples.

The javascript string trim() method is used to remove the whitespaces from the beginning and the end of a string and returns the new string.

trim() method is useful when we are taking the user input through an input box. At that time we don’t know whether the user-entered input contains whitespaces or not, in that scenario it is better to use the trim() method before performing any operation on the input.

Syntax

Here is the syntax of the trim() method:

Here, str is any string.

Parameters

trim() method takes in no parameters.

Return Value

It returns a new string with removed whitespaces from the beginning and the end.

If the string has no whitespaces then it returns a copy of the original string.

Note: trim() method doesn’t change the original string.

Example 1: Remove Whitespaces Using trim() Method

// Remove Whitespaces Using trim() Method
const str = '   Hello world!   ';

// before using trim
console.log(str); 
// Output: "   Hello, World!   "

// after using trim
console.log(str.trim()); 
// Output: Hello, World!

Output

"   Hello, World!   "
“Hello, World!”

In the above example, we have used trim() method to remove the whitespaces of the string str.

You can also notice that trim() method doesn’t change the original string, instead, it returns a new string.

Example 2: Remove Whitespaces of User Entered String

//  Remove Whitespaces of User Entered String
const str = prompt("Enter some text: ");

// before using trim
console.log(str); 

// after using trim
console.log(str.trim()); 

Output

Enter some text: "   Hello, World!   "
Hello, World!

In the above example, we first used prompt() to take string input from the user. If the string contains whitespaces at the beginning or the end, the trim() method will return a new string with removed whitespaces, else copy of the original string will be returned.

Leave a Comment

Your email address will not be published. Required fields are marked *