简体   繁体   中英

JavaScript regular expression of wrap text

I tried to wrap text using regular expression, to auto line break when detected \n or over the maximum of character each line, but here have some problem.

var str = ”The \na\nexample textttttttt, hello world, good bye.”

str.replace(/(?![^\n]{1,10}$)([^\n]{1,10})\s/g, '$1\n');
//replace line break when have \n or over maximum length
console.log(str);

The result

The
a
example
textttttttt,
hello
world,
good bye.

This regular expression can make a auto line break when detected \n or over maximum length (10) each line.

In line 3 of the result, the length of texttttttt, is over 10, may I know how to prevent this problem? When the word is over than maximum length.

The result which I want

The
a
example
texttttttt
t, hello
world,
good bye.

Update

The recently result of my output was wrong, the true result: It work event if the word over 10

The 

a

example te
xtttttttt,
 hello wor
ld, good b
ye.

You can use Negative Lookahead to check if you don't have the \n in front of character

 const str = "The \na\nexample textttttttt, hello world, good bye."; const words = str.match(/(?:(?<.\\n),){1;10}/g). console.log(words)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM