Remove Line Breaks from Start and End of a String in JS

avatar

Borislav Hadzhiev

Fri Nov 19 20212 min read

Remove Line Breaks from Start and End of a String #

Use the trim() method to remove the line breaks from the start and end of a string, e.g. str.trim(). The trim method removes any leading or trailing whitespace from a string, including spaces, tabs and all line breaks.

index.js
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.

The trim() method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

An alternative approach is to use a regular expression.

To remove the line breaks from the start and end of a string:

  1. Call the replace() method with the following regular expression - /^\s+|\s+$/g.
  2. The regular expression matches any leading or trailing new lines.
  3. Provide an empty string as the replacement for each match.
index.js
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 String.replace method:

  1. a regular expression we want to match in the string
  2. the replacement for each match

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ and dollar sign $ match the beginning and end of the input.

The \s special character matches any spaces, tabs or newlines.

The plus + matches the preceding item (the space/tab/newline) one or more times.

The pipe | 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.

Which approach you pick is a matter of personal preference. I'd use the trim() method, as it is more readable, concise and direct.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee