Home > Software engineering >  Remove all line breaks except from the last line
Remove all line breaks except from the last line

Time:11-23

I know how to remove all line breaks from a string, so for instance if some string is:

Robert Robertson,

1234 NW Bobcat Lane,

St. Robert,

(555) 555-1234

When using .replace(/(\r\n|\n|\r)/gm, " ") the output would be: "Robert Robertson, 1234 NW Bobcat Lane, St. Robert, (555) 555-1234"

What I want to achieve however is that all line breaks are removed EXCEPT the last one, so that the mobile phone number would be in its own line. So the output I want is:

Robert Robertson, 1234 NW Bobcat Lane, St. Robert,

(555) 555-1234

Can someone guide me in the right direction? Much appreciated.

CodePudding user response:

You can use

const text = "Robert Robertson,\n1234 NW Bobcat Lane,\nSt. Robert,\n(555) 555-1234"
console.log(text.replace(/(?:\r\n?|\n)(?=.*[\r\n])/g, " "));

Details:

  • (?:\r\n?|\n) - CRLF, LF or CR line ending
  • (?=.*[\r\n]) - that is immediately followed with any zero or more chars other than line break chars as many as possible (.*) and then either CR or LF char.
  • Related