Trim spaces while maintaining line breaks

I need to trim leading and trailing spaces from a multi-line string. I tried this regex using the String replacement method:

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

However, only in lines with spaces, line breaks are lost in the process. For example, (^ stands for space):

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

outputs this:

 1234 5678 90 

I want to use regex to save the third (empty) line:

 1234 5678 90 
+4
source share
1 answer

"\ s" matches any space character, newlines. Thus, to implement a finish that works as you wish, you must replace "\ s" with a regular space character (or a group of characters that will be treated as a space).

 string.replace(/^ +| +$/gm, ""); 
+5
source

Source: https://habr.com/ru/post/1391851/


All Articles