Skip to content

Instantly share code, notes, and snippets.

@mikomatic
Created July 11, 2013 09:32
Show Gist options
  • Save mikomatic/5974020 to your computer and use it in GitHub Desktop.
Save mikomatic/5974020 to your computer and use it in GitHub Desktop.
Random javascript functions: - linkfy - detect url in text ans transforms them to links - agoTime, helper to display a date twitter like (eg. 5 days ago)
function timeDiff(current, previous) {
var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - previous;
if (elapsed < msPerMinute) {
return Math.round(elapsed / 1000) + ' seconds ago';
} else if (elapsed < msPerHour) {
return Math.round(elapsed / msPerMinute) + ' minutes ago';
} else if (elapsed < msPerDay) {
return Math.round(elapsed / msPerHour) + ' hours ago';
} else if (elapsed < msPerMonth) {
return '...' + Math.round(elapsed / msPerDay) + ' days ago';
} else if (elapsed < msPerYear) {
return '...' + Math.round(elapsed / msPerMonth) + ' months ago';
} else {
return '...' + Math.round(elapsed / msPerYear) + ' years ago';
}
}
function agoTimeText(aTime) {
var current = new Date().getTime();
var previous = new Date(Date.parse(aTime)).getTime();
var agoTime = timeDiff(current, previous);
return agoTime;
}
function linkify(inputText) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /\w+@[a-zA-Z_]+?(?:\.[a-zA-Z]{2,6})+/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment