Javascript Regex在每n个单词后添加<br/> - 没有CSS

时间:2017-04-21 22:59:25

标签: javascript regex

我正在尝试写一个正则表达式,但我似乎无处可去。

我的判决如下:

"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解决方案。我不确定是否可以使用正则表达式。

1 个答案:

答案 0 :(得分:3)

编写一个选择3个单词的正则表达式,然后用附加的<br>替换它。

&#13;
&#13;
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;
&#13;
&#13;