Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming spaces while preserving line breaks

I need to trim the leading and trailing spaces from a multiline string. I've tried this regex with the String replace method:

String.replace(/^\s+|\s+$/gm, "");

However, on lines with spaces only, the line break is lost in the process. For instance (^ denotes a space):

^^^^1234^^^^
^^^^5678^^^^
^^^^^^^
^^90^^

outputs this :

1234
5678
90

What regex should I use to preserve the third (empty) line:

1234
5678

90
like image 670
Nicolas Le Thierry d'Ennequin Avatar asked Jan 19 '12 14:01

Nicolas Le Thierry d'Ennequin


People also ask

Does trim remove line breaks?

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.

How do you preserve spaces and line breaks in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks.

How do you trim a space at the end of a string?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

Which HTML tag do we use to preserve whitespace and carriage return?

Solution with the HTML <pre> tag The HTML <pre> which is used to put a preformatted text into an HTML document preserves spaces and line breaks of the text.


1 Answers

"\s" matches any whitespace character, new-lines as well. So to implement trim that works as you want, you have to replace "\s" with regular space character (or group of characters that will be treated as space).

string.replace(/^ +| +$/gm, "");
like image 80
WTK Avatar answered Sep 22 '22 05:09

WTK