Jquery 如何使用正则表达式为字符串中的用户名和哈希标记着色
我目前正在使用正则表达式为每条推文中的用户名上色Jquery 如何使用正则表达式为字符串中的用户名和哈希标记着色,jquery,regex,wordpress,twitter,Jquery,Regex,Wordpress,Twitter,我目前正在使用正则表达式为每条推文中的用户名上色 $('.tweet span').each(function() { $(this).html($(this).text().replace(/@[a-z0-1A-Z]+/g, '<span class="blue">$&</span>')); }); $('.tweet span')。每个(函数(){ $(this).html($(this).text().replace(/@[a-z0-1A-Z]+/
$('.tweet span').each(function() {
$(this).html($(this).text().replace(/@[a-z0-1A-Z]+/g, '<span class="blue">$&</span>'));
});
$('.tweet span')。每个(函数(){
$(this).html($(this).text().replace(/@[a-z0-1A-Z]+//g,$&');
});
我来扩展这个正则表达式,让它也为hashtags着色怎么样?试试这个:
$('.tweet span')。每个(函数(){
$(this.html($(this.text().replace(/(@|#))\w+/g,$&');
});代码>
.blue{
颜色:蓝色;
字体大小:粗体;
}
Kanye、Kim和Katy在纪梵希。这只是#PFW明星云集的礼服的开始:http://yhoo.it/182wjqd
我建议如下:
// because we're updating the html, we *use* the html() method,
// which automatically supplies the html as a string to the
// anonymous function (the 'h' below):
$('.tweet span').html(function(i, h) {
// a slightly more simple (or concise) regular expression,
// to match either a '@' or a '#' followed by a string
// of alphanumerics or underscore:
var reg = /(@|#)\w+/g;
// returning the original HTML after the replacement,
// passing the matched string ('match') to the anonymous
// function:
return h.replace(reg, function(match) {
// identifying whether the match is a hash or @user
// by the first character of the match:
switch (match.charAt(0)) {
case '#':
// if it's a hash, we return the match wrapped in
// a span with the class of 'hash':
return '<span class="hash">' + match + '</span>';
break;
case '@':
// otherwise, if it's an @username, we return the
// match wrapped in a span of class="user":
return '<span class="user">' + match + '</span>';
break;
// if neither of those matches, we simply return the
// unwrapped match:
default:
return match;
break;
};
});
});
- 为了@benjamin的利益,这是一条难以置信的tweet