-
Notifications
You must be signed in to change notification settings - Fork 32
/
jquery.linkify.js
67 lines (60 loc) · 2.11 KB
/
jquery.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function linkify(string, buildHashtagUrl, includeW3, target, noFollow) {
relNoFollow = "";
if (noFollow) {
relNoFollow = " rel=\"nofollow\"";
}
if (string.toLowerCase().indexOf("www.") === 0 && includeW3) {
string = '<a href="http://' + string + '" target="' + target + '"' + relNoFollow + '>' + string + '</a>';
} else {
string = '<a href="' + string + '" target="' + target + '"' + relNoFollow + '>' + string + '</a>';
}
if (buildHashtagUrl) {
string = string.replace(/\B#(\w+)/g, '<a href=' + buildHashtagUrl("$1") + ' target="' + target + '"' + relNoFollow + '>#$1</a>');
}
return string;
}
(function($) {
$.fn.linkify = function(opts) {
return this.each(function() {
var buildHashtagUrl;
var includeW3 = true;
var target = '_self';
var noFollow = true;
var regex = /((http|https|ftp)\:\/\/|\bw{3}\.)[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z\u00C0-\u017F0-9\-\._\?\,\'\/\\\+&%\$#\=~])*/gi;
var txt = this.innerHTML;
var output = '';
var replacement;
var matchLen;
var lastIndex = 0;
if (opts) {
if (typeof opts == "function") {
buildHashtagUrl = opts;
} else {
if (typeof opts.hashtagUrlBuilder == "function") {
buildHashtagUrl = opts.hashtagUrlBuilder;
}
if (typeof opts.includeW3 == "boolean") {
includeW3 = opts.includeW3;
}
if (typeof opts.target == "string") {
target = opts.target;
}
if (typeof opts.noFollow == "boolean") {
noFollow = opts.noFollow;
}
}
}
while ((match = regex.exec(txt)) !== null) {
matchLen = match[0].length;
replacement = linkify(match[0], buildHashtagUrl, includeW3, target, noFollow);
output += txt.substring(lastIndex, match.index + matchLen).replace(match[0], replacement);
lastIndex = match.index + matchLen;
}
// Include the rest of the text.
if (lastIndex !== txt.length) {
output += txt.substring(lastIndex);
}
$(this).html(output);
});
};
})(jQuery);