-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sanitize.js
More file actions
56 lines (47 loc) · 1.49 KB
/
test_sanitize.js
File metadata and controls
56 lines (47 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const { JSDOM } = require('jsdom');
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
global.document = dom.window.document;
function sanitizeHtml(html) {
const temp = document.createElement('div');
temp.innerHTML = html;
let hasContent = false;
const processNode = (node) => {
if (node.nodeType === 3) {
let text = node.textContent || '';
text = text.replace(/[\u00A0\s]+/g, ' ');
if (text.trim()) hasContent = true;
return text;
}
if (node.nodeType !== 1) return '';
const tagName = node.tagName.toLowerCase();
let childContent = '';
node.childNodes.forEach(child => {
childContent += processNode(child);
});
switch (tagName) {
case 'br': return hasContent ? '<br>' : '';
case 'div':
case 'p':
if (childContent.trim()) {
if (hasContent) return '<br>' + childContent.trim();
return childContent.trim();
}
if (childContent.includes('<br>') && hasContent) return '<br>';
return '';
default:
return childContent;
}
};
let result = '';
temp.childNodes.forEach(child => {
result += processNode(child);
});
return result
.replace(/^(<br\s*\/?>)+/, '')
.replace(/(<br\s*\/?>)+$/, '')
.replace(/(<br\s*\/?>){2,}/g, '<br>')
.trim();
}
const input1 = 'Olá amigos<div><br></div><div>Tudo joia?</div>';
console.log('Input:', JSON.stringify(input1));
console.log('Output:', sanitizeHtml(input1));