Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Using regex to insert hard line breaks to wrap text to a maximum line length, on spaces when possible

I'm having a bit of trouble figuring out the correct way to code my regex expression. Basically I want to insert hard line breaks (<br>) into a string. Let's say I want the maximum line length to be 10 characters. I want to insert a <br> at the nearest space before the 11th character, and right before the 11th character if the current line has no spaces within its 10 characters. If the last line has less than 10 characters we do nothing.

Example: Hello there, my name is Bob -> Hello <br>there, my <br>name is <br>Bob

Example: HelloThereMyName -> HelloThere<br>MyName

My current regex expression is:

x.replace(/[\s\S]{1,10}(?!\S)/g, '$&<br>')
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For the example data and desired result, you could either match 10 times any character except a newline followed by a space, or match 10 non whitespace characters.

In the replacement you can use the full match $& followed by <br>

Note that in your pattern [\s\S] matches any character including a newline. Using (?!\S) will assert a whitspace boundary to the right, and will not match the last space if there is one.

.{1,10} |\S{10}

See a egex demo

For example

const regex = /.{1,10} |\S{10}/g;
const str = `Hello there, my name is Bob
HelloThereMyName
nothing
name is Bob`;

console.log(str.replace(regex, `$&<br>`));

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda