Tom Tom - 4 months ago 12
Javascript Question

Javascript - removing space/s that are immediately followed by a linebreak

My problem is simple, but I cannot figure it out. I have a simple form (textarea) where user enters some text and this text is saved in a database. The issue is - I want to remove unnecessary spaces before the text is saved. So I created a simple Javascript function:

str.replace(/\n\s*\n\s*\n/g, '\n');


But it does not remove the spaces when user posts a text like:

hello world \nanother sample \n test


(so when user adds a space/spaces after the last word AND then posts another word in a new line, these spaces are left (and saved in database as):

hello word <br>another sample <br> test


etc.

What I need is that these spaces followed by a new line are removed by Javascript so that the result is:

hello word<br>another sample<br>test

Answer Source

Just need to simplify your regular expression:

const input = 'hello world     \nanother sample           \n test';
const output = input
  // Remove all whitespace before and after a linebreak
  .replace(/\s*\n\s*/g, '\n');
console.log(output);

Or if you want to see it as it will be saved in your database:

const input = 'hello world     \nanother sample           \n test';
const output = input
  // Remove all whitespace before and after a linebreak
  .replace(/\s*\n\s*/g, '<br>');
console.log(output);