Reputation: 6154
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
Upvotes: 8
Views: 3902
Reputation: 16961
"\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, "");
Upvotes: 12