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 incorporated into the loop it shows tweets from my twitter profile. I would like to know how to select the hashtags from these tweets (ex. #foo) and then apply a html link to the hashtag as follows...
<a class="hashtag" href="http://twitter.com/#search?q=foo">#foo</a>
The link has to also place the value of the hashtag (minus the #) into the #search?q= part of the link.
Is this possible and if so how would I go about doing this?
Thanks, Charlie Ryan
EDIT:
The hashtag #foo will be part of a h1, with no tags differentiating the one word such as
<h1>Lorem ipsum dolor sit amet #foo et adipiscing</h1>
So basically I need to find all strings begining with # and replace them with the link as seen above.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With