Home > Mobile >  Break HTML content after every 2 words
Break HTML content after every 2 words

Time:09-02

How to break HTML content after every 2 words using CSS and make it work for each possible word.

Example:

// Current HTML content
The community is here

// Expected outcome:
The community
is here

CodePudding user response:

I would not suggest using CSS in this case.

Example of how you could achieve it with regex:

let text = 'The community is here';
// Regex for linebreak after each second space.
let lineBreakText = text.replace(/^((\S \s ){1}\S )\s /, '$1<br>');
let element = document.getElementById('example');
element.innerHTML = lineBreakText;
<div id="example"></div>

S matches one or more non-space characters. \s matches one or more space characters. It will add a <br>tag for each second word.

  • Related