-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkify.js
50 lines (36 loc) · 928 Bytes
/
linkify.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
const linkify = require('linkifyjs');
const _tokenLength = function(token) {
let len = 0;
function _walk(t) {
if (typeof t.v == 'string') {
len += t.v.length;
} else if (Array.isArray(t.v)) {
for (let c of t.v) {
_walk(c);
}
}
}
_walk(token);
return len;
};
const tokenize = function tokenize(str) {
return linkify.parser.run(linkify.scanner.run(str));
};
// modified and lifted from linkify.find
const findLinkOffsets = (str) => {
const tokens = tokenize(str);
const filtered = [];
let offset = 0;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.isLink) {
const obj = token.toObject();
const valueLen = _tokenLength(token);
obj.offsets = [ offset, offset + valueLen ];
filtered.push(obj);
}
offset += _tokenLength(token);
}
return filtered;
};
module.exports = { findLinkOffsets };