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
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.
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.
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.
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.
"\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, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With