Search

Remove Whitespace Characters from Both Ends of a String

post-title

Sometimes you have a situation when you are comparing string or doing any opearation, but it returns as expected. This is because the string contains whitespace either beginning or ending of the string. This happens in case you have copied string with whitespace.

Example:

let earth = ' Hello earth, how are you? ';

So in this situation, if your string variable mostly from copy-pasted from another source, then it is advised that you remove whitespace from beginning or end of the string.

In this article, we will describe the techniques that you can use to remove whitespace from starting or ending of the string.

trim() method

trim method removes whitespace from the both side of the string.

Example:

let earth = '     Hello earth, how are you? ';
console.log(earth.trim()); // Hello earth, how are you?

 
trimStart() method

trimStart() method removes whitespace from the starting of the string.

Example:

let earth = '     Hello earth, how are you? ';
console.log(earth.trimStart()); // Hello earth, how are you?

trimEnd() method

trimEnd() method removes whitespace from the end of the string.

Example:

let earth = '     Hello earth, how are you? ';
console.log(earth.trimEnd()); //      Hello earth, how are you?

regular expression

If you want to use regular expression, this is also good way to remove string.

Example:

let earth = '     Hello earth, how are you? ';
earth = earth.replace(/(^\s+|\s+$)/g, '');
console.log(earth); // Hello earth, how are you?

I hope it will help you.