Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Format Text String to Tweet with JavaScript String.prototype
// Enable IE8 support for indexOf
if ( typeof Array.prototype.indexOf === 'undefined' ) {
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] === item) {
return i;
}
return -1;
}
}
}
// Setup format method for Tweet Mentions
String.prototype.setMentions = function() {
var re = /@[A-Z0-9_]+/gi;
return this.replace(re, function(match) {
return '<a href="https://twitter.com/' + match + '" target="_blank">' + match + '</a>';
});
};
// Setup format method for Tweet Hashtags
String.prototype.setHash = function() {
var re = /#[A-Z0-9_]+/gi;
return this.replace(re, function(match) {
return '<a href="https://twitter.com/search?q=' + encodeURIComponent(match) + '" target="_blank">' + match + '</a>';
});
};
// Setup format method for Tweet links
String.prototype.setUrl = function() {
var re = /(((f|ht){1}(tp|tps):\/\/)[-a-zA-Z0-9@:%_\+\.~#?&\/\/=]+)/gi;
return this.replace(re, function(match) {
return '<a href="' + match + '" target="_blank" class="link">' + match + '</a>';
});
};
// Collate all methods and format a string to Tweet
String.prototype.toTweet = function() {
var that;
self = this.setUrl();
self = self.setMentions();
self = self.setHash();
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment