Trim trailing spaces before each new line in a multi-line string I have a string from a multi-line plain text field and I'd like to trim any trailing spaces before new lines.

With plain regex I would use this expression: /\s*$/gm

Using

{{ string|replace('/\\s*$/', '') }}


will trim out the last trailing space of the string (same as the trim filter would), but not before every new line.

I have tried

{{ string|replace('/\\s*$/gm', '') }}


and

{{ string|replace('/\\s*$/m', '') }}


but that doesn't have any effect.

How can I apply the m modifier to the replace filter?
Currently it’s not possible to pass regex modifiers to the |replace filter. You’d have to just do this manually:

{% set str = "foo     \nbar    " %}
{% set trimmed = "" %}

{% for line in str|split("\n") %}
    {% set trimmed = trimmed ~ (trimmed ? "\n") ~ line|replace('/\\s*$/', '') %}
{% endfor %}


UPDATE

As of Craft 2.5, the |replace filter supports regex modifiers.