How to break lines according to a value

Asked

Viewed 669 times

2

How do I break lines according to the value ? For example a = 8. There I have a variable "d" q takes 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. Who can help me thank you, I tried some ideas but I was not successful.

  • But the b and the c do what ?

  • @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.

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 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);

  • muitoooo obrigado doooo.... I will read and etestar what you wrote. Thanks even guy.

Browser other questions tagged

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