labu77 labu77 - 2 months ago 22
jQuery Question

Use jQuery text() and replace + keep line breaks

I use

$("#test").html($("#test").text().replace(/([a-zA-Z]+[.,]? ){50}/,
function(x) { return x + "... <p>new content</p> ... "; }));


to add some content after 50 words. How is it possible in this case to keep the original line breaks of the full content?

I tried this

Alternative to jQuery text() function
https://www.sitepoint.com/jquery-text-function/

but with no success.

Example:

https://jsfiddle.net/3wkxzpo0/



$("#test").html($("#test").text().replace(/([a-zA-Z]+[.,]? ){50}/, function(x) { return x + "... <p style=\"background:red\">new content</p> ... "; }));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
Hallo, <br /><br />Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et duo dolores et ea rebum. Stet clita kasd gubergren, no sea <a href="/example.php">test</a> takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur <img src="sdfsdf">sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo
<br /><br />
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
<br /><br />
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet.
</div>




Answer

Here is a vanilla JS solution that iterates over the childNodes of the element, keeping track of the word count in each textNode and inserting the desired element when it reaches a certain word count.

var test = document.getElementById('test'), childNodes = test.childNodes,
    wordCount = 0, newHTML = [], maxWords = 50, toInsert = '&nbsp;<b>[50]</b>&nbsp;',
  i = 0, node = null, words = null, inserted = false;

for(i=0; i<childNodes.length; i++) {
  node = childNodes[i];
  if(node.nodeType !== 3) { // not a text node, append
    newHTML.push(node.outerHTML);
  }
  else { // is a text node, append till maxWords
    if(inserted) {
      newHTML.push(node.textContent);
    }
    else {
      words = node.textContent.replace(/^\s+/g, '').replace(/\s+$/g, '').split(/[\s\t\n+]/g);
      words = words.filter(function(_x) {
        return _x !== '';
      });
      if(wordCount + words.length < maxWords) {
        newHTML.push(node.textContent);
      }
      else {
        newHTML.push(words.slice(0, maxWords - wordCount).join(' '));
        newHTML.push(toInsert);
        newHTML.push(words.slice(maxWords - wordCount).join(' '));
        inserted = true;
      }
      wordCount += words.length;
    }
  }
}
test.innerHTML = newHTML.join('');

Demo: https://jsfiddle.net/5t6kq02g/1/