使用 jQuery 查找 twitter 主题标签,并应用链接 [英] Find twitter hashtags using jQuery, and apply a link
问题描述
首先我想说我不是 jQuery 专家,这似乎是一个非标准问题.
I'd like to start this off by saying I'm hardly a pro at jQuery, and this seems like a non-standard question.
基本上,我正在用 wordpress 制作一个博客,并将其合并到循环中,它会显示我的 twitter 个人资料中的推文.我想知道如何从这些推文中选择主题标签(例如#foo),然后将 html 链接应用到主题标签,如下所示...
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>
链接还必须将主题标签的值(减去 #)放入链接的 #search?q= 部分.
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?
谢谢,查理瑞恩
#foo 标签将成为 h1 的一部分,没有标签区分一个词,例如
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()));
});
});
编辑:我已将相关代码移到一个函数中,该函数接受带有主题标签的字符串,并返回标签替换为链接的相同字符串.它不依赖于 jQuery.
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()));
您只需将一个元素 html 值传递给它,并用调用 linkHashtags
的结果替换该值.人们可能会编写一个 jQuery 插件来使其更易于使用.
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.
那个正则表达式可能需要一些工作,我不确定在主题标签中允许使用哪些字符,但我想你明白了.
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.
这篇关于使用 jQuery 查找 twitter 主题标签,并应用链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!