Use split to split only text?

My code breaks the text and puts the html code after a certain number of words. This works, the problem is that the split function not only breaks the text, but also breaks the HTML. How to configure it only for text separation? Let's say I have an article, and I need a banner that appears in the middle of the article, if I do not take care, I would split some div or something like that.

Here is the code:

<script type="text/javascript"> jQuery(function($) { var wordList = $(".newsitem_text").html().split(' '); var newHtml = ''; $.each(wordList, function(index, word){ newHtml += ' ' + word; if (index == 10) { newHtml += 'Some HTML goes here' } }) ; $(".newsitem_text").html(newHtml); }); </script> 
+1
source share
1 answer

You should use the jQuery .contents() method and separate only the text tags when copying everything else verbatim. Something like that:

 jQuery(function($) { var newHtml = ''; var count = 0; function check() { if (count >= 20) { newHtml += 'Some HTML goes here' count = 0; } } $(".newsitem_text").contents().each(function () { if (this.nodeType != 3) { newHtml += this.outerHTML; count += $(this).text().trim().split(/\s+/).length; } else { var wordList = $(this).text().trim().split(/\s+/); $.each(wordList, function(index, word){ count++; check(); newHtml += ' ' + word; }) } }); check(); $(".newsitem_text").html(newHtml); }); 
+1
source

Source: https://habr.com/ru/post/1235444/


All Articles