Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jabranr/68515719cde0653d641d to your computer and use it in GitHub Desktop.
Save jabranr/68515719cde0653d641d to your computer and use it in GitHub Desktop.
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