JavaScript String trim() | Remove Whitespace From String

JavaScript String trim() | Remove Whitespace From String

In this tutorial, you’ll learn about JavaScript trim() method and how to use it.

JavaScript trim() method

The javascript String.trim()is a string method that is used to remove whitespace characters from the beginning and from the end of a string.

let res = str.trim();

Here,

  • The trim() method doesn’t change the original string.

if you want to remove only starting whitespace or ending whitespace from the given string, You can use javascript trimStart() or trimEnd() methods. See the followings:

In JavaScripttrimStart() is a string method that is used to remove whitespace characters from the start of a string.

In JavaScripttrimEnd() is a string method that is used to remove whitespace characters from the end of a string.

Note that, The whitespace characters include space, tab, no-break space, etc.

Examples: JavaScript trim()

Let’s take a took the following example:

Use the trim() to remove whitespace from both sides of a given string, see the following example:

let str = '  javascript programming  ';
let result = str.trim();

console.log(result);

Output:

"javascript programming"

Conclusion

In this tutorial, you have learned how to remove whitespace characters from both ends of a string using the js trim() method.

Leave a Reply

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