Jquery 返回匹配子字符串的数组
我有这个漂亮的函数,但我需要对它进行自定义,以便只返回与正则表达式匹配的项目数组。因此,结果将是Jquery 返回匹配子字符串的数组,jquery,regex,prototype,Jquery,Regex,Prototype,我有这个漂亮的函数,但我需要对它进行自定义,以便只返回与正则表达式匹配的项目数组。因此,结果将是#hash1234,#sweething,#一些不重要的东西使用此函数有什么方法可以做到这一点吗 String.prototype.parseHashtag = function() { return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) { var tag = t.replace("#", "%23");
#hash1234,#sweething,#一些不重要的东西
使用此函数有什么方法可以做到这一点吗
String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
var tag = t.replace("#", "%23");
return t.link("http://search.twitter.com/search?q=" + tag);
});
};
var string = '#hash1234 this is another hash: #sweetthing and yet another #something_notimportant';
$('#result').html(string.parseHashtag());
简单:
String.prototype.findHashTags = function() {
return this.match(/[#]+[A-Za-z0-9-_]+/g);
};
string.findHashTags()
// returns ["#hash1234", "#sweetthing", "#something_notimportant"]
模式完全相同。返回所有匹配项的数组,如果没有匹配项,则返回null
因此,如果对于不匹配的情况,null
是可接受的返回,那么:
String.prototype.parseHashtag = function() {
return this.match(/[#]+[A-Za-z0-9-_]+/g);
}
或者,如果希望返回空数组或其他不匹配的默认值:
String.prototype.parseHashtag = function() {
return this.match(/[#]+[A-Za-z0-9-_]+/g) || [];
}
使用匹配
String.prototype.parseHashtag = function() {
var t= this.match(/[#]+[A-Za-z0-9-_]+/g);
var tag='';
$.each(t,function(index,value) { tag = tag + value.replace('#','%23') + ','; });
return "http://search.twitter.com/search?q=" + tag;
};
var string = '#hash1234 this is another hash: #sweetthing and yet another #something_notimportant';
$('#result').html(string.parseHashtag());
”#hash1234这是另一个hash:#甜心和另一个#不重要的东西。匹配(/[#]+[A-Za-z0-9-#]+/g)。加入(“,”)
欢迎+1,很抱歉发布了几乎相同的答案,但在看到你的答案之前,我已经开始输入我的答案,我想包括当没有匹配时会发生什么的信息,所以当我看到你没有谈论我的答案时,我继续我的答案。。。