Categories
JavaScript Answers

How to Remove Whitespaces from the Start and End of a String with JavaScript?

Spread the love

To remove whitespaces from the start and end of a string with JavaScript, we can use the replace method to find the line breaks from the start and end of the string.

Then we can replace them all with empty strings.

For instance, we can write:

const str = '    Hello   ';
const trim = str.replace(/^\s+|\s+$/g, '');
console.log(trim);

We have the str string with spaces at the start and end of the string.

Then we call replace with /^\s+|\s+$/ gto match all the whitespaces at the start and end of the string.

^ means start of the string and $ matches the end.

g matches all instances of the spaces.

The 2nd argument is an empty string so we replace all the matches with empty strings.

Therefore, trim is 'Hello’ .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *