MCPcopy Index your code
hub / github.com/danvk/webdiff / html_substr

Function html_substr

ts/codediff/html-text-mapper.ts:22–80  ·  view source on GitHub ↗
(html: string, start: number, count: number)

Source from the content-addressed store, hash-verified

20// http://stackoverflow.com/questions/6003271/substring-text-with-html-tags-in-javascript?rq=1
21// http://stackoverflow.com/questions/16856928/substring-text-with-javascript-including-html-tags
22function html_substr(html: string, start: number, count: number) {
23 const div = document.createElement('div');
24 div.innerHTML = html;
25 let consumed = 0;
26
27 walk(div, track);
28
29 function track(el: Text) {
30 if (count > 0) {
31 let len = el.data.length;
32 if (start <= len) {
33 el.data = el.substringData(start, len);
34 start = 0;
35 } else {
36 start -= len;
37 el.data = '';
38 }
39 len = el.data.length;
40 count -= len;
41 consumed += len;
42 if (count <= 0) {
43 el.data = el.substringData(0, el.data.length + count);
44 }
45 } else {
46 el.data = '';
47 }
48 }
49
50 function walk(el: Node, fn: (node: Text) => void) {
51 let node = el.firstChild;
52 let oldNode;
53 const elsToRemove = [];
54 do {
55 if (node?.nodeType === 3) {
56 fn(node as Text);
57 } else if (node?.nodeType === 1 && node.childNodes.length > 0) {
58 walk(node, fn);
59 }
60 if (consumed == 0 && node?.nodeType == 1) {
61 elsToRemove.push(node);
62 }
63 } while ((node = node?.nextSibling ?? null) && count > 0);
64
65 // remove remaining nodes
66 while (node) {
67 oldNode = node;
68 node = node.nextSibling;
69 el.removeChild(oldNode);
70 }
71
72 for (const el of elsToRemove) {
73 if (el.parentNode) {
74 el.parentNode.removeChild(el);
75 }
76 }
77 }
78
79 return div.innerHTML;

Callers 1

getHtmlSubstringMethod · 0.85

Calls 1

walkFunction · 0.85

Tested by

no test coverage detected