Skip to content
the poor coder

.trim() method

Poor Man
Published
Reading time
1 min read
On this page

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:#

JavaScript
string.trim()

Example:#

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

JavaScript
const myString = "   Hello World!    ";

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

JavaScript
const trimmedString = myString.trim();

The value of trimmedString will be:

JavaScript
"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:
JavaScript
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:
JavaScript
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC