user9138698
user9138698

Reputation: 33

Remove all line breaks except from the last line

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.

Upvotes: 2

Views: 115

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627371

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.

Upvotes: 1

Related Questions