Simon
Simon

Reputation: 1374

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

I can't figure it out, how to change every nth line break to space.

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

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

It changes it all, but it should change every line break except the 3rd one, for example:

These lines should be changed to:

What regex should I use to get these results?

Upvotes: 4

Views: 126

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

You can use .replace callback function:

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);

Upvotes: 1

anubhava
anubhava

Reputation: 786291

You can capture each line into separate group and replace \n by space after 1st and 2nd group:

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

Upvotes: 2

Related Questions