Question

I am displaying Tweets on an HTML page, and will get tweets reading:

“Lorem ipsum dolor @username conspecetur.” or “Really loved @example's show”

How can I search this string for all twitter handles, and make them an achor tag linking to that user's twitter account?

Would be interested in something similar for #hashtags as well.

The HTML for a tweet looks like this The @usernames I want to convert to anchor tags are in <span class="tweet">

<div id="realtime_rollover_tweet_text">
    <a href="http://twitter.com/IsabelleOC/statuses/309314847345106945" class="twitter-handle" target="_blank">Isabelle O'Carroll</a>
    <span class="tweet">Forget ruffles and ridiculousness  check my kickass cycle outfit feat @NikeUK, @Sophie_Hulme, Ashish and @Topshop</span>
    <span class="category">bloggers</span>
</div>
Was it helpful?

Solution

The solution is pretty simple.. Just use .each iteration and replace the string with desired URL

UPDATED ANSWER

Working Demo : http://jsfiddle.net/cmzqv/1/

Solution : Use Regexp

   function(i,html) {
    return html.replace(/(@\w+)/g, '<span class="twitterHandle">$&</span>');
});

Working DEMO : http://jsfiddle.net/cmzqv/

Code :

$(document).ready(function(){
    $('.twitter').each(function() {
            var handle = $(this).text().slice(1);
        var handleUrl = "<span class='twitter'><a href='https://www.twitter.com/"+handle+"'>"+$(this).text()+"</a></span>";
               $(this).replaceWith(handleUrl); 
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top