-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (38 loc) · 946 Bytes
/
index.js
File metadata and controls
53 lines (38 loc) · 946 Bytes
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
var $ = require('cheerio');
function excerpts(html, opts) {
html = String(html);
opts = prepare(opts);
var text = $('<p>').html(html).text().trim()
.replace(/(\r\n|\r|\n|\s)+/g, ' ');
var excerpt = '';
if (opts.characters != null) {
excerpt = text.slice(0, opts.characters);
}
if (opts.words != null) {
excerpt = text.split(' ').slice(0, opts.words).join(' ');
}
if (excerpt.length < text.length) {
excerpt += opts.append;
}
return excerpt;
}
function prepare(opts) {
opts = opts || {};
if (opts.append == null) {
opts.append = '...';
}
if (!opts.words && !opts.characters) {
opts.words = 50;
}
if (opts.words && opts.characters) {
delete opts.characters;
}
if (opts.words != null) {
opts.words = parseInt(opts.words, 10);
}
if (opts.characters != null) {
opts.characters = parseInt(opts.characters, 10);
}
return opts;
}
module.exports = excerpts;