JavaScript String trim() method

The trim() method in JavaScript is used to remove whitespace from the beginning and end of a string. This method does not take any arguments, and returns a new string with the leading and trailing whitespace removed.

Here is an example of how the trim() method works:

const string1 = '   Hello, world!   ';

const result = string1.trim();

// the result will be: 'Hello, world!'

In the code example above, we first declare a string called string1 that contains the text ' Hello, world! '. This string contains whitespace at the beginning and end of the string. We then use the trim() method to remove the whitespace from the beginning and end of the string1 string. The trim() method does not take any arguments, so we simply call the method on the string1 string without passing any arguments.

As a result of calling the trim() method, the result variable will be set to 'Hello, world!', which is the string1 string with the leading and trailing whitespace removed. If the string1 string did not contain any leading or trailing whitespace, the result variable would be set to the original string1 string.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: