Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda