insert div inside a string after N word count without breaking html
<p>I'm trying to insert an ad inside text paragraph.</p>

<p>So far I've written this (<a href="https://jsfiddle.net/pv4m69jb/3/" rel="nofollow">jsfiddle</a>):</p>

<pre><code>$(function() {
  var $article   = $('#post-text').html();
  var totalChars = $article.length;
  var breakChars = 300;
  if (totalChars &gt; breakChars) {
    console.log(totalChars);
    var insertChars    = (breakChars - 10) + (totalChars - breakChars) * 0.2;
    var insertIndex    = $article.indexOf(' ', insertChars);
    var $articleWithAd = $article.substr(0,insertIndex) + '&lt;div id="adPlayer"&gt;bla bla&lt;/div&gt;&lt;p&gt;' + $article.substr(insertIndex + 1);
    $('#post-text').html($articleWithAd);
  }
});
</code></pre>

<p>I count total char length of the text. I set breakpoint which is minimum where I want to insert ad, for smaller texts I don't insert it at all.</p>

<p>I also use percentage algorithm to try to insert ad into different positions based on total count and min count.</p>

<p>This works perfectly except when I encounter html tags, as the fiddle case demonstrates if I insert into space between two classes <code>class="class class2"</code> all the hell breaks loose...</p>

<p>I want to use my code but improve it to ignore html tags.</p>

<p>any ideas?</p>