Reduce html to n characters while keeping the formatting Almost every language has a built-in function that can split a string at a given position. However, as soon as you have html tags in the string, the built-in function will not work properly.

Your task is to write a program or function which splits a string at the nth character but does not count characters of html tags and will output a valid html. The program must keep the formatting. Spaces outside the html tags may be counted or not counted, as you wish, but must be preserved. You can, however, exchange multiple consecutive spaces into a single space.

Input:


the string
the position to split at (0-based)


These can be taken as program or function arguments or can be read from the standard input.

Output: 
The split string which can be returned or written to the standard output.

The input will be valid html, it won't contain any entities (such as &amp;nbsp;). Tags that are opened after the character limit should be omitted from the output (see the last example). 

Example:

Input: &lt;i&gt;test&lt;/i&gt;, 3
Output: &lt;i&gt;tes&lt;/i&gt;

Input: &lt;strong&gt;&lt;i&gt;more&lt;/i&gt; &lt;span style="color: red"&gt;complicated&lt;/span&gt;&lt;/strong&gt;, 7
Output: &lt;strong&gt;&lt;i&gt;more&lt;/i&gt; &lt;span style="color: red"&gt;co&lt;/span&gt;&lt;/strong&gt;

Input: no html, 2
Output: no

Input: &lt;b&gt;no&lt;/b&gt; &lt;i&gt;html root&lt;/i&gt;, 5
Output: &lt;b&gt;no&lt;/b&gt; &lt;i&gt;ht&lt;/i&gt;

Input: &lt;b&gt;no img&lt;/b&gt;&lt;img src="test.png" /&gt;more text, 6
Output: &lt;b&gt;no img&lt;/b&gt;

You can use any language and the standard library of the given language. This is code golf, shortest program wins. Have fun!
This answer is no longer valid with the latest rule.

Javascript (ES6) 94 91

f=(s,l)=&gt;s.split(/(&lt;[^&gt;]+&gt;)/).map(x=&gt;x[0]=='&lt;'?x:[l--&gt;0?y:''for(y of x)].join('')).join('')




f('&lt;strong&gt;&lt;i&gt;more&lt;/i&gt; &lt;span style="color: red"&gt;complicated&lt;/span&gt;&lt;/strong&gt;', 7);
// '&lt;strong&gt;&lt;i&gt;more&lt;/i&gt; &lt;span style="color: red"&gt;co&lt;/span&gt;&lt;/strong&gt;'


Ungolfed:

f=(s,l)=&gt;
    s.split(/(&lt;[^&gt;]+&gt;)/). // split string s by &lt;*&gt;, capture group is spliced into the array 
    map(x=&gt; // map function to every item in the array
        x[0]=='&lt;'? // if first character is a &lt;
            x // don't modify the string
        : // else
            [ // array comprehension
                for(y of x) // for every character y in x
                    l--&gt;0? // if l &gt; 0 (and decrement l)
                        y // character y
                    : // else
                        '' // empty string 
            ].join('') // join characters in array
        ).
    join('') // join all strings in array