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+$/ g
to 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’
.