public
Last active

Replace URLs with links and unicode emoji with images.

  • Download Gist
handlebars-formatTextForHTML.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
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

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.