/ Published in: ActionScript 3
Encode a Tweet from a Twitter search query wrapping all hash tags, user names and urls with herf entities with one function call
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
package { /** * @author Ninjaparade */ public class TwitterStringUtil { public static function encodeTwitterString(tweet : String) : String { var twitterHash : RegExp = /(\#[a-zA-Z0-9_%]*)/g; var twitterUser : RegExp = /(\@[a-zA-Z0-9_%]+)/ig; var twitterLink : RegExp = /(https?:\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((\/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?/g; var str : String = tweet; var arr : Object = str.match(twitterLink); if (arr != null) { for each ( var s:String in arr ) { str = str.replace(s, encodeURL(s)); } } arr = str.match(twitterHash); if (arr != null) { for each (var k : String in arr) { str = str.replace(k, replaceHashtoURL(k)); } } arr = str.match(twitterUser); if (arr != null) { for each (var j : String in arr) { str = str.replace(j, replaceURL(j)); // str = "<a href = \"http://www.twitter.com/" + j.substr(1, j.length) + "\" " + "target=\"_blank\">" + j + "</a>"; } } return str; } public static function searchTwitterHash(value : String) : String { var pattern : RegExp = /(\#[a-zA-Z0-9_%]*)/g; var str : String = value; var arr : Object = value.match(pattern); // if(arr != null) { for each ( var s:String in arr ) { str = str.replace(s, replaceHashtoURL(s)); // } } return str; } public static function searchTwitterUser(value : String) : String { var pattern : RegExp = /(\@[a-zA-Z0-9_%]+)/ig; var str : String = value; var arr : Object = value.match(pattern); for each ( var s:String in arr ) { str = str.replace(s, replaceURL(s)); } return str; } public static function searchTwitterURL(value : String) : String { var pattern : RegExp = /(https?:\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((\/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?/g; var str : String = value; var arr : Object = value.match(pattern); if (arr != null) { for each ( var s:String in arr ) { str = str.replace(s, encodeURL(s)); } } return str; } public static function replaceURL(value : String) : String { var str : String = "<a href = \"http://www.twitter.com/" + value.substr(1, value.length) + "\" " + "target=\"_blank\">" + value + "</a>"; return str; } public static function replaceHashtoURL(value : String) : String { var str : String = "<a href = \"http://twitter.com/#search?q=%23" + value.substr(1, value.length) + "\" " + "target=\"_blank\">" + value + "</a>"; return str; } public static function encodeURL(value : String) : String { var str : String = "<a href = " + "\"" + value + "\" " + "target=\"_blank\">" + value + "</a>"; return str; } } }