Find twitter hashtags using jQuery, and apply a link

后端 未结 3 1171
面向向阳花
面向向阳花 2020-12-18 03:18

I\'d like to start this off by saying I\'m hardly a pro at jQuery, and this seems like a non-standard question.

Basically I\'m making a blog in wordpress, and incorp

相关标签:
3条回答
  • 2020-12-18 03:50

    Why are you want to doing this with jQuery? Use a Wordpress Plugin: Twittify! This plugin simply turns Twitter @usernames and `#hashtags into links to the related place on Twitter.

    You always should reduce changes in the DOM to a minimum.

    0 讨论(0)
  • 2020-12-18 03:55

    You don't need to mess around with complex regexs. When you request a user timeline from the Twitter API with /statuses/user_timeline, you can set a parameter called include_entities to true. See this page of documentation:

    http://dev.twitter.com/doc/get/statuses/user_timeline

    This will add a JSON object to every tweet called an entity. The entity will contain all the details about every hashtag in the tweet all neatly parsed out for you. You will get the text of the hashtag, and its starting and stopping positions in the tweet. You can just substitute a linkified version of the tag back into the text before displaying it.

    0 讨论(0)
  • 2020-12-18 04:15

    You would craft a regular expression to find those hashtags and replace them with a link, using backreferences to get the matching tag.

    hashtag_regexp = /#([a-zA-Z0-9]+)/g;
    
    function linkHashtags(text) {
        return text.replace(
            hashtag_regexp,
            '<a class="hashtag" href="http://twitter.com/#search?q=$1">#$1</a>'
        );
    } 
    
    $(document).ready(function(){
        $('p').each(function() {
            $(this).html(linkHashtags($(this).html()));
        });
    });
    

    Edit: I've moved the relevant code inside a function that accepts a string with hashtags, and returns the same string with the tags replaced by links. It doesn't rely on jQuery that way.

    $('p').html(linkHashtags($('p').html()));
    

    You just pass it an elements html value and replace the value by the result of calling linkHashtags. One could probably write a jQuery plugin to make this easier to use.

    Example

    That regular expression might need some work, I'm not sure which characters are allowed to be used inside a hashtag, but I think you get the idea.

    0 讨论(0)
提交回复
热议问题