How to trim a string in JavaScript with examples

Introduction :

Trimming is used to remove whitespace characters from a string. Javascript provides us different methods to remove whitespaces from the start, end and both sides of a string. Whitespace is any whitespace character like tab, space, LF, no-break space, etc.

In this tutorial, we will learn how to trim from the start, end and both sides of a string in Javascript with examples.

Remove whitespace from both sides of a string :

In Javascript, String.trim method is used to remove whitespaces from both sides of a string. This is defined as below :

str.trim()

This method doesn’t modify the original string. It removes whitespace from both ends of the string and returns this new string.

Example :

An example of str.trim() method :

var str1 = "  Hello World  ";
var str2 = `
Hello World
`;

console.log(str1);
console.log(str2);

console.log("Trim :")

console.log(str1.trim());
console.log(str2.trim());

It will print the below output :

  Hello World  

Hello World

Trim :
Hello World
Hello World

As you can see here, trim() removed the whitespace characters from both end for both str1 and str2.

Remove whitespace character from the start and end of a string :

Similar to trim(), we have two more methods called trimStart and trimEnd to remove whitespace characters from the start and end of a string. Let’s try this method with the same example we have seen above :

var str1 = "  Hello World  ";
var str2 = `
Hello World
`;

console.log(str1);
console.log(str2);

console.log("Trim :")

console.log(str1.trimStart());
console.log(str2.trimStart());

JavaScript trimstart example

Here, only the starting whitespace characters are removed. Similarly, if we use trimEnd(), it will produce one output like below :

JavaScript trimend example

Conclusion :

In this tutorial, we have learned how to trim a string in Javascript. We have learned three different methods for that. Try to run the above examples and drop one comment below if you have any queries.