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

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

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 doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

Alternatively, you can 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 arguments 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 to remove them.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN.

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.