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 can simplify and use directly in the function match
which 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 just use the method join
array by passing the \n
with parameter. If by chance the result is to show in html then you should use "<br>"
in the join
to have the appropriate line breaks.
If the value indicating the amount of requirements to break can change, or if it is read/built based on input user so already need to use RegExp
to construct 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);
But the
b
and thec
do what ?– Isac
@Isac I tried to simplify my question, I was a bit confused. The idea is .... I have a string and want to make line break always q get in the eighth character.
– Dan100