-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-sanitizer.js
75 lines (64 loc) · 2.13 KB
/
text-sanitizer.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const sanitizeHtml = require('sanitize-html');
const he = require('he');
const showdown = require('showdown');
const converter = new showdown.Converter();
converter.setOption('openLinksInNewWindow', true);
/**
* Strips all HTML tags from a string
* ensures the string is decoded (example '&' is transformed to '&')
*
* @param {string} text
* @returns String
*/
module.exports.stripMarkdownTags = function(text) {
if (!text) return '';
text = converter.makeHtml(text);
// to replace <br /> tag with line break \n char. Not sure how to do this with sanitize-html package
text = text.replace(/<br ?\/?>/g, '\n');
return he.decode(sanitizeHtml(text, {
allowedTags: [],
}));
};
/**
* Parses a string to be used as text parameter in the show or episode detail view.
* If no HTML tags, it wraps the string with a h3 tag.
* Else it transform the first p tag into a H3 tag for SEO reasons.
*
* @param {string} text
* @returns String
*/
module.exports.sanitizeText = function(text) {
text = converter.makeHtml(text);
text = sanitizeHtml(text, {
allowedTags: ['a', 'em', 'p', 'br'],
transformTags: {
'h1': 'p',
'h2': 'p',
'h3': 'p',
'h4': 'p',
'h5': 'p',
'h6': 'p',
},
});
/*
* For SEO we want at least one H3 tag in the text block
**/
text = text.replace(/<p>/, '<h3>');
text = text.replace(/<\/p>/, '</h3>');
return he.decode(text);
};
/**
* Creates an excerpt from text based upon word length.
* Adds an ellipsis to end of excerpt if word limit is less than word length of text.
*
* @param {string} text - Text to create excerpt from.
* @param {string} wordLimit - Number of words to cut the text at. Default is 104 (13 words * 8 lines).
* @return String
*/
module.exports.createExcerpt = function(text, wordLimit = 104) {
if (!text || text.length === 0) return "";
const textArray = text.split(" ");
let succeedingModifier = "";
if (textArray.length > wordLimit) succeedingModifier = "...";
return textArray.slice(0,wordLimit).join(" ") + succeedingModifier;
};