我正在尝试写一个正则表达式,但我似乎无处可去。
我的判决如下:
"Hey, diddle, diddle, The cat and the fiddle, The cow jumped over the moon; The little dog laughed To see such sport, And the dish ran away with the spoon."
我想每<br/>
个字n
添加一个3
。例如,如果我每"Hey, diddle, diddle,<br/>
The cat and<br/>
the fiddle, The<br/>
etc..."
个单词都这样做,它就会像这样......
slideToggle
我知道自动换行css,我纯粹在寻找一个javascript解决方案。我不确定是否可以使用正则表达式。
答案 0 :(得分:3)
编写一个选择3个单词的正则表达式,然后用附加的<br>
替换它。
function wordWrap(string, numWordsPerLine) {
return string.replace(
RegExp('(?:\\S+\\s*){' + numWordsPerLine + '}', 'g'),
'$&<br>'
);
}
var input = "Hey, diddle, diddle, The cat and the fiddle, The cow jumped over the moon; The little dog laughed To see such sport, And the dish ran away with the spoon.";
document.body.innerHTML = wordWrap(input, 3);
&#13;