2

Hi I'm still a newbie at javascript so I want to create a script that inserts a line break after every 3 lines. So here's my code I got so far

var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.toString().match(/.{3}/g).join('</br>');
console.log(newNum);

It is doing it wrong. It seems to be inserting every 3characters instead of lines. Can anyone help me fix the code?

2 Answers2

5

You can use the replace function. Try the below code.

var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/(.*\n.*\n.*\n)/g, '$1<br>');
console.log(newNum);

EDIT

I have made a few changes to the RegEx in the code below. This will allow you to specify the number of lines between which <br> need to be added.

var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/((.*\n){3})/g, '$1<br>');
console.log(newNum);

In the above RegEx, the .* will match all characters till the end of line and the \n will match the new line character.

(.*\n){3}

I have enclosed this in parenthesis to mark it as a group and used {3} to indicate that the preceding group repeats 3 times.

((.*\n){3})

Then the whole RegEx is enclosed in a parenthesis to use it as the first matched group that can be referenced in the replace section using $1.

You can replace the {3} with any number.

Vivek
  • 2,665
  • 1
  • 18
  • 20
1

You should avoid using string manipulation when using HTML string. Also using BR to break line is not a good idea as well. You should use a block element instead.

var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;

var content = document.querySelector('.content');

var urls = num.split('\n');
var temp;

for(var i = 0; i< urls.length; i++) {
  if(!temp || (i+1) % 3 === 0) {
    if (temp) content.appendChild(temp);
    temp = document.createElement('div');
  }
  
  var span = document.createElement('span');
  span.classList.add('link')
  span.innerHTML = urls[i];
  temp.appendChild(span);
}
content.appendChild(temp);
.link {
  margin: 5px;
}
<div class='content'>

Reference:

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79