How to break lines according to a value

2

How do I break lines by value? For example a = 8. Then I have a "d" variable that receives a string. var d="written work considered in its original wording". If I put an If = a; it traverses the string by always counting q for 8 characters it breaks the line. Anyone who can help me thanks, I tried some ideas but I was not successful.

    
asked by anonymous 30.09.2018 / 23:58

1 answer

1

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);
    
01.10.2018 / 00:46