Skip to content

Instantly share code, notes, and snippets.

@os0x
Created September 22, 2010 23:23
Show Gist options
  • Save os0x/592772 to your computer and use it in GitHub Desktop.
Save os0x/592772 to your computer and use it in GitHub Desktop.
var re_http = '(?:https?://\\S+)',
re_user = '(?:[@][0-9A-Za-z_]{1,15})',
re_hashtag = '(?:[#]\\S+)',
re_tweet = new RegExp(
'('+[re_http, re_user, re_hashtag].join('|')+'|\\S+)', 'g'
);
var make_link = function(href, txt) {
var a = document.createElement('a');
a.href = href;
a.appendChild(document.createTextNode(txt));
return a;
};
parse_tweet = function(str) {
var i, l, t, d = document,
ts = str.match(re_tweet),
fr = d.createDocumentFragment();
for (i = 0, l = ts.length; i < l; i++) {
t = ts[i];
if (t.match('^'+re_http)) {
fr.appendChild(make_link(t, t));
}else if (t.match('^'+re_user)) {
fr.appendChild(d.createTextNode('@'));
t = t.replace(/^[@]/,'');
fr.appendChild(make_link('http://twitter.com/' + t, t));
}else if (t.match('^'+re_hashtag)) {
fr.appendChild(make_link(
'http://twitter.com/search?q=' + encodeURIComponent(t), t
));
} else if (t) { /* t can be empty */
fr.appendChild(d.createTextNode(t));
}
}
return fr;
};
/*
var s='http://j.mp/dankogai @dankogai こうですか? #XSS わかりません\n\
http://twitter.com/#@"onmouseover="alert(location.href)"/ <script>alert(\'XSS\')</script>\n\
javascript:alert(1);http://s';
var d = document.createElement('div');
d.appendChild(parse_tweet(s));
alert(d.innerHTML);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment