简体   繁体   English

JavaScript 换行正则表达式

[英]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.我尝试使用正则表达式换行文本,以在检测到 \n 或超过每行的最大字符数时自动换行,但这里有一些问题。

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.当检测到 \n 或超过每行的最大长度 (10) 时,此正则表达式可以自动换行。

In line 3 of the result, the length of texttttttt, is over 10, may I know how to prevent this problem?结果的第3行,texttttttt的长度超过了10,请问如何避免这个问题? 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我的 output 最近的结果是错误的,真实的结果: 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您可以使用Negative Lookahead检查字符前面是否没有\n

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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