このような多くの動作は、正規表現を使用してシングルライナーとして実現できます (必要な動作に応じて、最小数の一致する文字を持つ貪欲でない量指定子、または最大数の文字を持つ貪欲な量指定子を使用します)。
以下では、ノード V8 REPL 内で機能する非貪欲なグローバル置換が示されているため、コマンドと結果を確認できます。ただし、ブラウザでも同じことが機能するはずです。
このパターンは、定義されたグループ ( \w は単語文字を意味し、\s は空白文字を意味します) に一致する少なくとも 10 文字を検索し、\b 単語境界に対してパターンを固定します。次に、後方参照を使用して、元の一致を改行が追加されたものに置き換えます (この場合、括弧で囲まれた後方参照でキャプチャされていないスペース文字をオプションで置き換えます)。
> s = "This is a paragraph with several words in it."
'This is a paragraph with several words in it.'
> s.replace(/([\w\s]{10,}?)\s?\b/g, "$1\n")
'This is a \nparagraph \nwith several\nwords in it\n.'
元の投稿者が要求した形式では、これは次のようになります...
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
function wordWrap(text,width){
var re = new RegExp("([\\w\\s]{" + (width - 2) + ",}?\\w)\\s?\\b", "g")
return text.replace(re,"$1\n")
}
> wordWrap(str,40)
'Lorem Ipsum is simply dummy text of the\nprinting and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s\n, when an unknown printer took a galley of\ntype and scrambled it to make a type specimen\nbook. It has survived not only five centuries\n, but also the leap into electronic typesetting\n, remaining essentially unchanged. It w as popularised in the 1960s with the\nrelease of Letraset sheets containing Lorem\nIpsum passages, and more recently with desktop publishing\nsoftware like Aldus PageMaker including\nversions of Lorem Ipsum.'