Javascript正则表达式添加后每n个单词-没有CSS

时间:2022-02-02 21:45:02

I'm trying to write a regex but I seem to be getting nowhere with it.

我正试图写一个regex,但我似乎没有任何进展。

I have a sentence as follow:

我有一个句子:

"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."

I want to add a <br/> every n number of words. For example if I did it every 3 words it would look like this...

每n个单词加一个
。例如,如果我每三个字写一次,就会是这样……

"Hey, diddle, diddle,<br/>
The cat and<br/>
the fiddle, The<br/>
etc..."

I know about word wrap css and I purely am looking for a javascript solution to this. I'm not sure if it is possible with regex.

我知道word wrap css,我只是在寻找一个javascript解决方案。我不确定使用regex是否可行。

1 个解决方案

#1


3  

Write a regex that selects 3 words, and then replace it with a <br> appended.

写一个regex,选择3个单词,然后用
替换它。

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);

#1


3  

Write a regex that selects 3 words, and then replace it with a <br> appended.

写一个regex,选择3个单词,然后用
替换它。

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);