Change every line break except the nth line break with regex on js

I cannot figure out how to change every nth row in space.

I have this regex code to change all line breaks to spaces:

this.value.replace(/\n/g, ' ');

It changes everything, but it must change every line break except the third, for example:

  • line1
  • line2
  • li3
  • li4
  • li5
  • Li6

These lines should be changed to:

  • line1 line2 li3
  • li4 li5 li6

What regular expression should be used to get these results?

+4
source share
2 answers

You can record each line in a separate group and replace \non spaceafter the 1st and 2nd groups:

var re = /([^\n]*)\n([^\n]*)\n([^\n]*)(\n|$)/g; 
var str = 'line1\nline2\nli3\nli4\nli5\nli6';

var result = str.replace(re, '$1 $2 $3$4');

RegEx Demo

+2
source

.replace:

function replaceLineBreaks(text) {
   var index = 1;
   return text.replace(/\n/g, function(){  
      return index++ % 3 == 0 ? '\n' : ' ';  
   });
}

var replacedText = replaceLineBreaks(text);

Demo:

var text = "line1\n\
  line2\n\
  line3\n\
  line4\n\
  line5\n\
  line6\n";

function replaceLineBreaks(text) {
   var index = 1;
   return text.replace(/\n/g, function() {
      return index++ % 3 == 0 ? '<br>' : ' '; //br for testing purposes
   });
}

document.body.innerHTML = replaceLineBreaks(text);
Hide result
+1

Source: https://habr.com/ru/post/1627677/


All Articles