How to add a character in a string, which is already divided, to each N character?

1

I need to know how to separate, in line breaks, one string to each N character. However, before separating each N characters, they have already been separated by each comma .

  

I want this separation to be a break in the output.

Only the comma is very simple, just a split(",").join("\n") that already solves. But a separation within another separation I can not. I even think of some solutions but all very large, and for my code I need something simple.

For example, one separation every 6 characters:

Entry:

teste,testando,outro teste

Output:

teste
testan
do
outro 
teste
    
asked by anonymous 08.06.2018 / 16:13

1 answer

3

To do the missing part you can use a regex, which would be the most direct.

The regex would be:

/.{1,6}/g

Any caratere (meaning . ) with quantity 1 to 6, applied globally ( g ). When used with match it will give you an array of results for every 6 letters. In order to stay as shown, just do join("\n") , as you have in your example, which will give you a \n every 6 letters.

Then only the application part of the regex would be:

.match(/.{1,6}/g).join("\n")

The rest is the logic you already have. Combining everything would look like this:

let texto = "teste,testando,outro teste";
let resultados = texto.split(",").map(t => t.match(/.{1,6}/g).join("\n"));

alert(resultados.join("\n"));

First divide by , , then transform each result into sets of 6 letters with the regex followed by join . In the end it shows everything along with join("\n") .

Documentation:

08.06.2018 / 16:35