Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Replace URLs with links and unicode emoji with images.
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
@ustun

This comment has been minimized.

Show comment Hide comment
@ustun

ustun Jan 25, 2013

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.

ustun commented Jan 25, 2013

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.

@siddo420

This comment has been minimized.

Show comment Hide comment
@siddo420

siddo420 Jun 16, 2017

Thanks for the gist.

Any plans to fix the bug that does not allow http://backbonejs.org/#Events-listenTo URLs?

Thanks for the gist.

Any plans to fix the bug that does not allow http://backbonejs.org/#Events-listenTo URLs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment