简体   繁体   中英

Regex - replace multiple line breaks with two line break and remove line break if at the end?

I'm doing this (+ JSON.stringify()) for sending linebreaks via ajax to my mysql server:

var newChatComment = varChatComment.replace(/\r\n|\r|\n/g,'\n');

How can I also replace multiple line breaks with two line break and in case of if the line break(s) is(are) at the end ... remove the line break?

  • plus in case of only one line break ... keep this line break at one?

Edit: The duplicate example pointed to doesn't consider the fact to remove the line break in case the line break is at the end. So this is a new question

If you need to keep a single line break at the start of the string, use

 var varChatComment = "\\r\\n\\n1\\r\\n2\\n\\n\\n3\\r\\r\\n4\\r\\n\\r\\n"; var newChatComment = varChatComment.replace(/((?:\\r\\n?|\\n)+)$|(?:\\r\\n?|\\n){2,}/g, function ($0,$1) { return $1 ? '' : '\\n\\n'; }); console.log(newChatComment); 

Note that the pattern is built around a (?:\\r\\n?|\\n) construct that matches:

  • \\r\\n? - a CR and an optional LF
  • | - or
  • \\n - an LF symbol.

Details :

  • ((?:\\r\\n?|\\n)+)$ - 1 or more line breaks at the end of the string (those will be removed)
  • | - or
  • (?:\\r\\n?|\\n){2,} - 2 or more line breaks (any style) (this will be turned into 2 newlines.

The ((?:\\r\\n?|\\n)+)$| alternative matches any line break(s) at the end of the string, and if found, these ones are replaced with the empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM