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
replace() methods to do this.
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
let str1 = '\nHello, \nThis is LearnShareIT\n\n'; let newStr1 = str1.trim(); console.log('Original string: '+ str1); console.log('New string: '+ newStr1);
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?
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:
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);
Original string: Today is Monday New string: Today is Monday
\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
There are two simple methods to remove line breaks from start and end of a string in JS:
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:
Name of the university: HVNH BA
Major: htttql MIS