Nick
Nick

Reputation: 14293

How to add a newline every three character in javascript

How can i split a string that contains | (pipe) as separator lets after every 3 pipes?

I'll explain better:

i have a string that results in dates, something like this:

Tuesday - 23-06-2015| Wednesday - 24-06-2015| Thursday - 25-06-2015| Friday - 26-06-2015| Monday - 29-06-2015| Tuesday - 30-06-2015|

And i'd like to add a <br/> so that i have only 3 dates on the same line, like this:

Tuesday - 23-06-2015| Wednesday - 24-06-2015| Thursday - 25-06-2015|

Friday - 26-06-2015| Monday - 29-06-2015| Tuesday - 30-06-2015|

I found this code to count the times the pipe is repeated in the string:

var CustomerDatesSplitted = (customerDates.match(/\|/g) || []).length;
console.log(CustomerDatesSplitted ); //Logs 6, the right value

and i found this code that needs a specific value to insert in the regex (in this case, adds a new line after 10 charactes:

customerDates.match(/.{1,10}/g).join("<br/>");

but i don't know the best way to make it "dynamic" so that it checks only the pipes and split after the 3rd, 6th, 9th and so on...

suggestions?

Upvotes: 1

Views: 231

Answers (1)

anubhava
anubhava

Reputation: 785631

You can do:

str = str.replace(/((?:[^|]*\|){3})/g, '$1<br>');

RegEx Demo

Upvotes: 4

Related Questions