How To Remove Line Breaks From Start And End Of A String In JS

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

If you want to remove line breaks from start and end of a string in JS and keep the line breaks in the string, read this article to the end. I’ll show you the straightforward trim() and replace() methods to do this.

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

Using trim() method

The trim() method removes spaces from both ends of a string. Note that the trim() method only removes spaces in the JavasSript string at the beginning and the end of the string, not the spaces in the middle.

And the spaces that strim() can remove here include common spaces (created by the spacebar) and spaces created by tabs or line breaks.

Here’s a look at specific examples that use the trim() method to break lines at the beginning and the end of a JavaScript string:

Code sample:

let str1 = '\nHello, \nThis is LearnShareIT\n\n';
let newStr1 = str1.trim();
console.log('Original string: '+ str1);
console.log('New string: '+ newStr1);

Output

Original string:
Hello,
This is LearnShareIT


New string: Hello,
This is LearnShareIT

From the examples above, you can see that the line breaks at the beginning and the end of the string has been removed, while the spaces between the strings are still preserved, right?

In JavaScript, using the trim() method will not change the original string but save the result as a new string. Therefore, assign the result of the deletion to a variable so that the variable can use many times in the program.

Using replace() method

Another popular way is to use the replace() function with an argument of a RegEx regular expression in the glocal flag format to remove line breaks from the start and end of a string

We use RegEx to represent line breaks as a glocal flag of /^\n+|\n+$/g and remove line breaks at the beginning and the end of the string as follows:

Code sample:

let str2 = '\nToday is \n\n Monday\n\n';
let newStr2 = str2.replace(/^\n+|\n+$/g,'');
console.log('Original string: '+ str2);
console.log('New string: ' + newStr2);

Output

Original string:
Today is

 Monday


New string: Today is

 Monday

The expressions:

  • \n : find the line break character
  • + : check the character appears one or more times
  • ^ : check the starting character of the string
  • $ : check the string terminator character

Summary

There are two simple methods to remove line breaks from start and end of a string in JS: trim() and replace(). I always prefer to use trim() because it’s easy to use and doesn’t have to remember expressions like when using replace(). Hope you have understood and successfully applied to your problem. Thanks for reading, and see you soon!

Maybe you are interested:

Leave a Reply

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