Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Taking into consideration that <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">parsing html with regex is a bad idea</a>, here is a solution that does just that :)</p> <p><em>EDIT: Just to be clear: This is not a valid solution, it was meant as an exercise that made very lenient assumptions about the input string, and as such should be taken with a grain of salt. Read the link above and see why parsing html with regex can never be done.</em></p> <pre><code>function htmlSubstring(s, n) { var m, r = /&lt;([^&gt;\s]*)[^&gt;]*&gt;/g, stack = [], lasti = 0, result = ''; //for each tag, while we don't have enough characters while ((m = r.exec(s)) &amp;&amp; n) { //get the text substring between the last tag and this one var temp = s.substring(lasti, m.index).substr(0, n); //append to the result and count the number of characters added result += temp; n -= temp.length; lasti = r.lastIndex; if (n) { result += m[0]; if (m[1].indexOf('/') === 0) { //if this is a closing tag, than pop the stack (does not account for bad html) stack.pop(); } else if (m[1].lastIndexOf('/') !== m[1].length - 1) { //if this is not a self closing tag than push it in the stack stack.push(m[1]); } } } //add the remainder of the string, if needed (there are no more tags in here) result += s.substr(lasti, n); //fix the unclosed tags while (stack.length) { result += '&lt;/' + stack.pop() + '&gt;'; } return result; } </code></pre> <p><strong>Example:</strong> <a href="http://jsfiddle.net/danmana/5mNNU/" rel="nofollow noreferrer">http://jsfiddle.net/danmana/5mNNU/</a></p> <p>Note: <a href="https://stackoverflow.com/questions/6003271/substring-text-with-html-tags-in-javascript/6003713#6003713">patrick dw's solution</a> may be safer regarding bad html, but I'm not sure how well it handles white spaces.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload