[英]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.