Created
January 22, 2012 00:08
-
-
Save arbales/1654670 to your computer and use it in GitHub Desktop.
Replace URLs with links and unicode emoji with images.
This file contains 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
LINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi | |
EMOJI_DIRECTORY = "/path/to/assets/emoji/20x20" | |
# Handlebars is presumed, but you could swap out | |
ESCAPE_EXPRESSION_FUNCTION = Handlebars.Utils.escapeExpression | |
MARKSAFE_FUNCTION = (str) -> new Handlebars.SafeString(str) | |
# Emoji unicode chars become images. | |
emojify = (safeContent) -> | |
safeContent.replace /([\ue001-\ue537])/g, (emoji) -> | |
filename = emoji.charCodeAt(0).toString(16).toUpperCase() | |
"<img class='emoji' src='#{EMOJI_DIRECTORY}/#{filename}.png'/>" # TODO: alt and title | |
# Replace URLs like https://github.com with <a href='https://github.com'>github.com</a> | |
linkify = (safeContent) -> | |
safeContent.replace LINK_DETECTION_REGEX, (url) -> | |
address = if /[a-z]+:\/\//.test url then url else "http://#{url}" | |
url = url.replace /^https?:\/\//, '' | |
"<a href='#{address}' target='_blank'>#{url}</a>" | |
# Helper for formatting strings with links and line breaks for display in HTML | |
formatTextForHTML = (content) -> | |
# Start by escaping expressions in the content to make them safe. | |
safeContent = ESCAPE_EXPRESSION_FUNCTION(content) | |
safeContent = linkify safeContent | |
# Line breaks become <br/>'s | |
safeContent = safeContent.replace /\n/g, '<br/>' | |
safeContent = emojify safeContent | |
MARKSAFE_FUNCTION(safeContent) # Mark our string as safe, since it is. | |
Handlebars.registerHelper 'formatTextForHTML', formatTextForHTML |
Thanks for the gist.
Any plans to fix the bug that does not allow http://backbonejs.org/#Events-listenTo URLs?
The regex really is almost perfect. One issue is if you end a sentence with a link, then it does not detect, like, "For more information check out our site at www.mysite.com. There you can find anything your heart desires!"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came here from the SO thread. This regex is almost perfect. Unfortunately, this fails on URLs which contain a hash sign. For example it fails to detect: http://backbonejs.org/#Events-listenTo
I have found Gruber's link detection regexp, but haven't gotten it working in JS yet. Maybe that one is more robust.