forked from STRML/strml.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplaceURLs.js
More file actions
22 lines (20 loc) · 998 Bytes
/
replaceURLs.js
File metadata and controls
22 lines (20 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const urlRegex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w\-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w!\/]*))?)/g;
export default function createAnchors(message) {
return regexReplace(message, urlRegex, function(match) {
// Don't break <img src="http:..." /> or mailtos or other anchors
if (/(src=|href=|mailto:)/.test(message.slice(message.indexOf(match) - 7).slice(0, 7))) return match;
let href = match;
if (match.slice(0, 4) !== 'http') href = 'http://' + href;
return '<a href="' + href + '" target="_blank">' + match.replace('www.', '') + '</a>';
});
};
// Simple regex replace function.
export function regexReplace(message, regex, replace) {
const match = message.match(regex);
if (match && match.length) {
for (let i = 0; i < match.length; i++) {
message = message.replace(match[i], (typeof replace === 'function' ? replace(match[i]) : replace));
}
}
return message;
}