繁体   English   中英

JavaScript 换行正则表达式

[英]JavaScript regular expression of wrap text

我尝试使用正则表达式换行文本,以在检测到 \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
a
example
textttttttt,
hello
world,
good bye.

当检测到 \n 或超过每行的最大长度 (10) 时,此正则表达式可以自动换行。

结果的第3行,texttttttt的长度超过了10,请问如何避免这个问题? 当单词超过最大长度时。

我想要的结果

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

更新

我的 output 最近的结果是错误的,真实的结果: It work event if the word over 10

The 

a

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

您可以使用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