Skip to content

Instantly share code, notes, and snippets.

@skyl
Created February 22, 2012 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyl/1881068 to your computer and use it in GitHub Desktop.
Save skyl/1881068 to your computer and use it in GitHub Desktop.
linkify phone numbers in coffeescript
s = """
Extensions are not supported.
Alphabetic phonenumbers eg 1888-FOR-RILZ are not supported.
Of course, you'll want to prevent injection by stripping html tags first.
It switches the numbers to international format (or sth) - suggestions welcome!
706 555 5001put some
ill formed(404) 555-1397text in here
+34712938479 to make it interesting...5
404.555.1239.
1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901 # this one will not work, who does that anyways?
it would catch stuff like 2012/12/21/5/10/45 and such
we don't want to catch
http://sth.com/23458029340940920349.html
we do want to catch <p>706 3384109</p>
12345678901
hrm, but might it catch a copyright year range?
this one, no, not enough characters:
1999-2008
weeded out for consecutive non-numeric:
1990 - 2010
2009- 2010
GO FORTH AND FIND THE EDGE CASES!
"""
window.telephone_linkify = (str) ->
re = /[\s|>][0-9\(\)\+\-][0-9\(\)\+ \-\.]{8,15}[0-9]/gm
matches = str.match(re)
if matches
idx = 0
for match in matches
# this is where we weed out matches that
# shouldn't be phone numbers, hrm ...
if match.match(/[\(\)\+ \-\.\>]{3}|[\+ \-\.\>]{2}/)
continue
done = str.slice(0, idx)
left = str.slice(idx, str.length)
newstr = match.replace(/\(|\)|\+| |\-|\.|\>/g, "")
replacement = "<a href='tel:+#{newstr}'>#{newstr}</a>"
idx = (str.indexOf match) + 1 + replacement.length
newleft = left.replace(match.slice(1, match.length), replacement)
str = done + newleft
str
alert telephone_linkify(s)
@skyl
Copy link
Author

skyl commented Feb 26, 2012

this is borked, md5 hashes can get identified as phone numbers ;/

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