Last active
April 24, 2023 10:53
-
-
Save jabranr/68515719cde0653d641d to your computer and use it in GitHub Desktop.
Format Text String to Tweet with JavaScript String.prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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