2017-04-21 29 views
2

我想寫一個正則表達式,但我似乎沒有得到它與它。Javascript正則表達式添加<br>後每n個單詞 - 沒有CSS

我有一句話如下:

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

我知道換行CSS和我純粹是尋找一個JavaScript的解決了這一點。我不確定這是否可能與正則表達式。

回答

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

+0

爲什麼額外的'\'在S之前? –

+1

@AlexanderSolonik額外的反斜槓是需要的,因爲我使用字符串文字而不是正則表達式,所以我必須避免反斜槓。 – 4castle

相關問題