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

Asked

Viewed 60 times

1

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

I want that in the output this separation is line break.

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

For example, a separation every 6 characters:

Entree:

teste,testando,outro teste

Exit:

teste
testan
do
outro 
teste

1 answer

3


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

The regex would be:

/.{1,6}/g

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

Then only the part of the regex application would be:

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

The rest is the logic that already has. Combining everything would be 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 transforms each result into sets of 6 letters with regex followed by join. In the end it shows everything together with join("\n").

Documentation:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.