This post will discuss how to trim a string in JavaScript and jQuery.

Trimming removes all whitespace characters from both ends of a string. Only the whitespace characters in the middle of the string is preserved. There are several ways to trim a string in JavaScript. Here are some of the most common functions:

1. Using String.trim() function

The String.trim() function removes all whitespace characters and all the line terminator characters from both ends of a string and returns a new string, without modifying the original. For example:

Download  Run Code

 
This function is supported by all modern browsers and is part of the ECMAScript 5 standard. Even though it is supported by all major browsers, here is a polyfill for trim() function provided by MDN:

 
We can also use the String.trimStart() and String.trimEnd() functions to remove whitespace from only one end of a string. These functions are part of the ECMAScript 2019 standard and are not supported by all browsers yet. For example:

Download  Run Code

2. Using jQuery library

The jQuery’s $.trim() function is a convenience function also removes all white spaces at the beginning and the end of the string. It is useful if we are already using jQuery in our project. Unlike trim(), this function handles undefined and null values gracefully. For example:

Download Code

3. Using Lodash library

Alternatively, we can use the _.trim() function by lodash, which will remove the leading and trailing whitespace from the string. We can also specify the characters to be trimmed as the second argument to the _.trim() function. If we want to trim only one end of the string, we can use the _.trimStart() or _.trimEnd() functions by lodash, as needed. For example:

Download Code

4. Using regular expression

We can also use a regular expression to remove whitespace or any other characters from a string. The String.replace() function gives us more control over what we want to trim, but it is also more verbose and complex. For example, to remove all whitespace characters from both ends of a string, we can use:

Download  Run Code

That’s all about trimming a string in JavaScript and jQuery.