Removing white spaces in string (trim) with JavaScript

November 1, 2021

Removing white spaces in string (trim) with JavaScript

In this article we’ll observe a native JavaScript method, which will solve the problem of removing white spaces in string

Removing white spaces in string cover

Hey you programmer, okay? Let’s learn something new!

Watch this content:

We often don’t have control about the data type we receive, both from the backend and from the user

So it is necessary to remove spaces in string database, so that the text can be used

We can do this easily using JavaScript, and its trim() method

Let’s learn how to use it:

let texto = ' \n teste \n ';
console.log(texto.trim()); // teste

In this example the trim ignored all blank spaces and even the skipping line (\n)

So we have a powerful and native JavaScript tool to remove blank space from a string. It sounds easy right?

Remembering that the trim method returns the clean string, so we need to assign this value to a variable

It doesn’t change the original string, so be careful! 

Another important point: blank spaces can be among words, end or in the beginning of the string

So a sentence would be ‘destroyed’ by the method, as even the blank spaces among words would be removed


We’ve seen that removing white spaces in string in string is very easy applying JavaScript

Just use the trim method, and we are returned the pure string without the extra spaces

Do you want to learn more about JavaScript and modern web development techniques? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x