1

Using the jQuery text function I received a string that contains a lot of carriage returns/line breaks in sequence.

For example, ā€œ\r\n \r\n \r\n Welcome Bob\r\n\t \r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n Recommendation: Hellot\r\n\r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\nā€ .

Is it possible to have just one line break instead of a sequence using JavaScript, presumably replace function?

Alex
  • 7,007
  • 18
  • 69
  • 114

2 Answers2

2

Use

str.replace(/\s*?[\r\n]\s*/g, "\n");

to match any whitespaces around your carriage returns/linebreaks and replace them by \n altogether.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

The JavaScript replace function only replaces the first match. You'll have to use a regular expression to achieve what you want.

str.replace(/(\r\n[ \t]*)+/g, "\r\n");

A more extensive SO answer here.

For the regex: (\r\n[ \t]*)+:

(         # start group
\r\n      # match your newlines
[ \t]*    # match zero or more spaces and tabs
)         # end group
+         # match all the above once or more times
Community
  • 1
  • 1
Laoujin
  • 9,962
  • 7
  • 42
  • 69