I am trying to make any "@sometext" an HTML link, where "sometext" is also appended to the url. that is, '@sometext' becomes a link to ' http://someurl.com/sometext '. But that can change, because the connection will be different every time depending on what "sometext" is. I am writing this in javascript and jquery. I'm trying to recreate links like the ones on Twitter when someone inserts the @username name that links to that person’s profile page.
I already have code to search for URLs in the text and create HTML links. But I don't have anything written for what I'm trying to do now with the @ symbol. I could not find anything to help me.
This is the code I have to do for link urls:
var message = this.text;
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@
message = message.replace(exp,"<a href='$1' target='_new'>$1</a>");
resultDiv += message + "</div>";
Ok, so this is what my code looks like now, and it works, except that for some @sometext links there is a line ":" immediately following the line, @sometext: and therefore the link is a broken link. How can I remove or ignore ':' when creating a URL as an HTML link?
$(data.results).each(function() {
var userLink = "<a href=\"http://twitter.com/" + this.from_user + "\">";
var replyTo = this.to_user;
var resultDiv = "<div class=\"finalResult\">";
resultDiv += "<fieldset class=\"tweetReturn\" style = \"width: 75%;\">";
resultDiv += "<div><div id=\"userImage\"><img src=\"" + this.profile_image_url + "\" height=\"48px\" width=\"48px\"/></div>";
resultDiv += "<div id=\"userMessage\"><strong>" + userLink + this.from_user + "</a></strong> ";
var message = this.text;
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
message = message.replace(exp,"<a href='$1'>$1</a>");
message = message.replace( /(^|\s)@(\S+)/g, '$1@<a href=\"http://twitter.com/$2\">$2</a>');
message = message.replace( /(^|\s)#(\S+)/g, '$1<a href=\"http://search.twitter.com/search?q=%23\$2\">#$2</a>');
resultDiv += message + "</div>";
resultDiv += "<div id=\"twitterLink\"><a href=\"http://www.twitter.com\"><img src=\"http://twitter-badges.s3.amazonaws.com/twitter-b.png\" alt=\"Visit Twitter\"/></a></div>"
resultDiv += "<div id=\"timestamp\">" + this.created_at + "</div>";
resultDiv += "</div></div></fieldset>";
resultDiv += '</div><br />';
$("#displayResults").append(resultDiv);
});
source
share