15

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)

2 Answers 2

24

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

Sign up to request clarification or add additional context in comments.

2 Comments

What about if I would like to include leading spaces in replace(/[^\S\r\n]+$/gm, "") ?
@leonard vertighel - This one should do the trick: replace(/^[^\S\r\n]+|[^\S\r\n]+$/gm, "")
0

Use String.prototype.trimEnd() (or trim()):

multilineText.split('\n').map(line => line.trimEnd()).join('\n');

Regex are hard to read and understand, favor simple functions composition when possible.

const multilineText = '  quick   \n brown   \n  fox     \n';

const multilineTextTrimmed = multilineText
  .split('\n')
  .map(line => line.trimEnd())
  .join('\n');

console.log(multilineTextTrimmed);

console.assert(multilineTextTrimmed === '  quick\n brown\n  fox\n');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.