You can solve this problem with a simple regular expression in the form of:
/.{1,8}/g
Explanation:
/ - Inicio da expressão regular
. - Qualquer caratere
{1,8} - Entre 1 a 8 vezes, sempre apanhando o máximo possível.
/ - Fim da expressão regular
g - Aplicado globalmente na string
If this number never changes, you can simplify it and use it directly in the match
that returns an array as a result:
let texto = "obra escrita considerada na sua redação original";
let blocosTexto = texto.match(/.{1,8}/g);
let textoQuebrado = blocosTexto.join("\n");
console.log(textoQuebrado);
Since the value obtained is an array, to construct a text with line breaks for each array value, use the join
of array passing \n
with parameter. If by chance the result is to show in html then you should use "<br>"
in join
to have the appropriate line breaks.
If the value that indicates how many pieces of data to break can change, or if it is read / constructed based on the user's input then you need to use RegExp
to build the regular expression:
let texto = "obra escrita considerada na sua redação original";
let quebra = 8;
let regex = new RegExp('.{1,${quebra}}', 'g');
let blocosTexto = texto.match(regex);
let textoQuebrado = blocosTexto.join("\n");
console.log(textoQuebrado);