.trim() method

What is the .trim() method in JavaScript?

The .trim() method is a built-in method in JavaScript that removes whitespace characters (spaces, tabs, newlines, etc.) from both ends of a string. It does not modify the original string, but returns a new string with the whitespace characters removed.

Syntax:

string.trim()

Example:

Let's say we have a string with some extra whitespace at the beginning and end:

const myString = "   Hello World!    ";

If we use the .trim() method on this string:

const trimmedString = myString.trim();

The value of trimmedString will be:

"Hello World!"

Notice how the extra whitespace at the beginning and end of the original string has been removed.

Multiple Ways to Use .trim():

  • You can chain the .trim() method with other string methods, like this:
const myString = "   Hello World!    ";
const trimmedAndUppercased = myString.trim().toUpperCase();

Here, we first trim the whitespace from the beginning and end of myString, and then convert the resulting string to uppercase using the .toUpperCase() method.

  • You can also pass a regular expression to the .trim() method to remove other characters besides whitespace. For example, to remove all leading or trailing exclamation marks from a string, you could use:
const myString = "!!!Hello World!!!";
const trimmedString = myString.trim(/!+/g);

Here, we pass the regular expression /!+/g to the .trim() method, which matches one or more exclamation marks at the beginning or end of the string and removes them.

In summary, the .trim() method is a useful tool for removing whitespace characters from the beginning and end of a string in JavaScript. By understanding how to use this method, you can improve the readability and usability of your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe