wkkok345
wkkok345

Reputation: 21

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

Upvotes: 2

Views: 1219

Answers (1)

The fourth bird
The fourth bird

Reputation: 163477

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

Upvotes: 1

Related Questions