Web development and Tech news Blog site. WEBISFREE.com

HOME > lodash

[lodash] How to use the trim() function and examples

Last Modified : 04 Mar, 2023 / Created : 04 Mar, 2023
View Count

We will learn about the usage of the trim() method in lodash, which is one way to remove whitespace from a string.

# lodash trim() method

trim() is a method that is applied to strings. Generally, the trim() function is commonly used. When using trim(), it removes the spaces used at the beginning and end of the string. For example, ' abc ' will be converted to 'abc'.

The usage of lodash trim() is as follows.

_.trim(string, char)

The trim() function can receive two parameters. The first one represents the value to input, while the second one indicates the whitespace or string to apply.

// string : Transformation, string to be changed.
// char(Option) : When converting or changing, the character that serves as a reference is removed from the corresponding value.

The trim() function accepts two arguments, and the second argument, char, allows trim() to remove characters other than whitespace.

Then, let's create some examples below and find out the results.

! lodash trim() Examples

The following shows how applying the trim() method to various strings produces different results.

First, we want to remove any leading whitespace.
_.trim('  Webisfree.com');

// result

I also want to remove the whitespace at the end.
_.trim(' Webisfree.com  ');

// result

If you want to remove the equal sign (=) instead of the space, follow the steps below.

// result

This time, it's the case when white spaces and = characters exist together. In this case, they can be used together as shown below. As you can see, the second argument is '=' with a white space.
_.trim('  ===Webisfree.com===  ', ' =');

// result

We have looked at a few examples together up to this point. Using the trim() function like this is an effective and convenient way to easily remove leading and trailing spaces and specific characters.

Perhaps you're looking for the following text as well?


    [lodash] Understanding the fromPairs() method


    Exploring the lodash startsWith() Method