Created
August 23, 2010 23:07
-
-
Save tiff/546532 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| autoLinkUrls = (function() { | |
| /** | |
| * Converts urls starting with "www" or "http(s)" to clickable links | |
| * | |
| * Inspired by rails' "auto_link_urls" method | |
| * http://apidock.com/rails/ActionView/Helpers/TextHelper/auto_link_urls | |
| */ | |
| var URL_REG_EXP = /(https?:\/\/|www\.)[^\s<]+/gi, | |
| TRAILING_CHAR_REG_EXP = /([^\w\/-])$/i, | |
| MAX_DISPLAY_LENGTH = 55, | |
| TRUNCATION = "...", | |
| BRACKETS = { | |
| ")": "(", | |
| "]": "[", | |
| "}": "{" | |
| }; | |
| function truncate(url, maxLength) { | |
| return url.length > maxLength ? url.slice(0, maxLength - TRUNCATION.length) + TRUNCATION : url; | |
| } | |
| return function(str) { | |
| return str.replace(URL_REG_EXP, function(url) { | |
| var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", | |
| opening = BRACKETS[punctuation]; | |
| url = url.replace(TRAILING_CHAR_REG_EXP, ""); | |
| if (url.split(opening).length > url.split(punctuation).length) { | |
| url = url + punctuation; | |
| punctuation = ""; | |
| } | |
| var realUrl = url, | |
| displayUrl = truncate(url, MAX_DISPLAY_LENGTH); | |
| // Add http prefix if necessary | |
| if (realUrl.substr(0, 4) == "www.") { | |
| realUrl = "http://" + realUrl; | |
| } | |
| return '<a href="' + realUrl + '" target="_blank">' + displayUrl + '</a>' + punctuation; | |
| }); | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment