Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!