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

后端 未结 1 542
无人及你
无人及你 2021-01-04 13:59

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

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

What regular expression to use

相关标签:
1条回答
  • 2021-01-04 14:37

    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 讨论(0)
提交回复
热议问题