1

In javascript, I am trying to write a regex that will remove all spaces between occurrences of \n.

For example, the string Test\n \n \n \n\n 1234 would turn into Test\n\n\n\n\n 1234.

How do I do this?

5
  • Why not use .trim() ? Commented Jun 6, 2022 at 14:14
  • @arnaud_h Probably because they want to keep the newlines. Commented Jun 6, 2022 at 14:15
  • Can use .replaceAll() Commented Jun 6, 2022 at 14:17
  • replacing this regex ^([\s\t]*)\n$ with "\n" would work? it should match every single line replacing the space part before the newline with nothing but a newline. Commented Jun 6, 2022 at 14:18
  • I think \n + would work.. just replace with new line. Commented Jun 6, 2022 at 14:18

2 Answers 2

3

You can use non-greedy matching of whitespace \s*? bracketed by lookbehind and lookahead assertions for \n, (expressed as (?<=\n) and (?=\n) respectively) and replace it with an empty string.

const input = "Test\n \n \n    \n\n 1234";
const result = input.replace(/(?<=\n)\s*?(?=\n)/g, '');

console.log(JSON.stringify(result));

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

Comments

0

let t = "test\n\n \n\n\n \n"

console.log(JSON.stringify(t.replaceAll(/(?<=\n)\s*?(?=\n)/g, '')))

1 Comment

I don't want to replace all spaces. Just ones between newlines.

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.