Fri Nov 19 2021·2 min read
Photo by Jordan McQueen
trim() method to remove the line breaks from the start and end of a
trim method removes any leading or trailing
whitespace from a string, including spaces, tabs and all line breaks.
const str = '\none two\n'; // ✅ Using trim() const result1 = str.trim(); console.log(result1); // 👉️ "one two" // ✅ using Regular expression const result2 = str.replace(/^\s+|\s+$/g, ''); console.log(result2); // 👉️ "one two"
The String.trim method removes any line breaks from the start and end of a string.
It handles all line terminator characters (LF, CR, etc).
The method also removes any leading or trailing spaces or tabs.
An alternative approach is to use a regular expression.
To remove the line breaks from the start and end of a string:
replace()method with the following regular expression -
const str = '\none two\n'; const result2 = str.replace(/^\s+|\s+$/g, ''); console.log(result2); // 👉️ "one two"
We passed the following
2 parameters to the
The forward slashes
/ / mark the beginning and end of the regular expression.
^ and dollar sign
$ match the beginning and end of the input.
\s special character matches any spaces, tabs or newlines.
+ matches the preceding item (the space/tab/newline) one or more
| means "or", in other words, we match any spaces, tabs, or newlines
at the beginning or end of the string and replace them with an empty string,
practically removing them.
If you ever need help reading a regular expression, check out this regex cheatsheet from MDN. It's by far the best one out there.
trim()method, as it is more readable, concise and direct.