Remove Whitespace Characters from Both Ends of a String

  243 views   7 months ago Javascript

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]