UNPKG

html-truncate-ts

Version:

TypeScript library for truncating HTML strings while preserving HTML tags and structure

3 lines (2 loc) 2.01 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HtmlTruncate={})}(this,function(e){"use strict";const t={},s=["img","br"],n='([\\w|-]+\\s*=\\s*"[^"]*"\\s*)*',i="\\s*\\/?\\s*",r=new RegExp("<\\/?\\w+\\s*"+n+"\\s*\\/\\s*>"),l=new RegExp("<\\/?\\w+\\s*"+n+i+">"),o=/(((ftp|https?):\/\/)[-\w@:%_+.~#?,&//=]+)|((mailto:)?[_.\w-]+@([\w][\w-]+\.)+[a-zA-Z]{2,3})/g,f=new RegExp("<img\\s*"+n+i+">"),d=new RegExp("\\W+","g"),u=e=>{let t=e.indexOf(" ");if(-1===t&&(t=e.indexOf(">"),-1===t))throw new Error("HTML tag is not well-formed : "+e);return e.substring(1,t)},g=(e,t,s,n,i)=>{const r=10>t?t:10,{truncateLastWord:l,slop:o}=i||{},f=t-s,u=f<(o||r),g=u?f:(o||r)-1,p=u?0:f-(o||r),a=n||f+(o||r);let c,x,b=f;if(!l){if(c=e.slice(p,a),n&&c.length<=n)b=c.length;else for(;null!==(x=d.exec(c));){if(!(x.index<g)){if(x.index===g){b=f;break}b=f+(x.index-g);break}if(b=f-(g-x.index),0===x.index&&f<=1)break}e.charAt(b-1).match(/\s$/)&&b--}return b};e.truncate=(e,n,i)=>{const d=10>n?n:10,p=[];let a,c,x,b,h,w=0,m="";for((i=i||t).ellipsis=void 0!==i.ellipsis?i.ellipsis:"...",i.truncateLastWord=void 0===i.truncateLastWord||i.truncateLastWord,i.slop=void 0!==i.slop?i.slop:d;a=l.exec(e);){if(c=a[0],x=a.index,w+x>n){m+=e.substring(0,g(e,n,w,x,i));break}w+=x,m+=e.substring(0,x),"/"===c[1]?(p.pop(),h=null):(h=r.exec(c),h||(b=u(c),p.push(b))),m+=h?h[0]:c,e=e.substring(x+c.length)}if(w>=n);else if(a=o.exec(e),!a||a.index>=n)m+=e.substring(0,g(e,n,w,void 0,i));else for(;a;)c=a[0],x=a.index,m+=e.substring(0,x+c.length-w),e=e.substring(x+c.length),a=o.exec(e);return e.length>n-w&&i.ellipsis&&(m+=i.ellipsis),m+=(e=>{let t="";return e.reverse().forEach(e=>{-1===s.indexOf(e)&&(t+="</"+e+">")}),t})(p),i.keepImageTag||(m=(e=>{const t=f.exec(e);let s,n;return t?(s=t.index,n=t[0].length,e.substring(0,s)+e.substring(s+n)):e})(m)),m}}); //# sourceMappingURL=html-truncate.min.js.map