Gods
Gods

Reputation: 149

Replace every Nth whitespace with line break

I'm trying to replace every 3rd whitespace with a newline character. Here is what I have so far:

text.replace(/(\s{3})/g, "$1<br />")

However, nothing gets replaced.

Upvotes: 2

Views: 1569

Answers (1)

Tushar
Tushar

Reputation: 87203

You can use following regex

((?:.*?\s){2}.*?)\s

OR

((?:\S*\s){2}.*?)\s

RegEx Explanation:

  1. (?:.*?\s){2}: Match any characters until first space twice
  2. .*?: Match anything lazily
  3. \S*: Match any number of non-space characters
  4. \s: Match a single space character

Code:

text = text.replace(/((?:.*?\s){2}.*?)\s/g, '$1<br />');

var text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

document.body.innerHTML = text.replace(/((?:.*?\s){2}.*?)\s/g, '$1<br />');

Upvotes: 2

Related Questions