使用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?
谢谢, 查理·瑞安(Charlie Ryan)
Thanks, Charlie Ryan
井号标签#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屋!