Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim trailing spaces before newlines in a single multi-line string in JavaScript

Say I have this single string, here I denote spaces (" ") with ^

^^quick^^^\n
^brown^^^\n
^^fox^^^^^\n

What regular expression to use to remove trailing spaces with .replace()? using replace(/\s+$/g, "") not really helpful since that only removes the spaces on the last line with "fox".

Going through other questions I found that replace(/\s+(?:$|\n)/g,"") matches the right sections but also gets rid of the new line characters but I do need them.

So the perfect result will be:

^^quick\n
^brown\n
^^fox\n

(only trailing spaces are removed everything else stays)

like image 943
Recct Avatar asked Apr 06 '11 15:04

Recct


1 Answers

Add the 'm' multi-line modifier.

replace(/\s+$/gm, "")

Or faster still...

replace(/\s\s*$/gm, "")

Why is this faster? See: Faster JavaScript Trim

Addendum: The above expression has the potentially unwanted effect of compressing adjacent newlines. If this is not the desired behavior then the following pattern is preferred:

replace(/[^\S\r\n]+$/gm, "")

Edited 2013-11-17: - Added alternative pattern which does not compress consecutive newlines. (Thanks to dalgard for pointing this deficiency out.)

like image 176
ridgerunner Avatar answered Oct 27 '22 14:10

ridgerunner