开发者

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)


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜