Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mjumbewu/5986956 to your computer and use it in GitHub Desktop.
Save mjumbewu/5986956 to your computer and use it in GitHub Desktop.
Now matches things like "I got this from http://github.com/, and it's great!" as well. The trailing comma would throw it off before.
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, (match, url) ->
address = if /[a-z]+:\/\//.test url then url else "http://#{url}"
match = match.replace /^https?:\/\//, ''
"<a href='#{address}' target='_blank'>#{match}</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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment