2012-11-06 65 views
2

我有这个漂亮的功能,但我需要定制它只返回匹配正则表达式的项目数组。所以结果将是#hash1234, #sweetthing,#something_notimportant有没有什么办法可以使用这个函数来做到这一点?返回匹配的子串数组

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()); 
+1

''#hash1234这是另一种散列:#sweetthing和又一#something_notimportant'.match(/ [#] + [A-ZA-Z0-9 -_] + /克)。加入(” ,“)' – nhahtdh

回答

3

.match method返回所有匹配的数组,或者如果没有匹配返回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) || []; 
} 
2

简单:

String.prototype.findHashTags = function() { 
    return this.match(/[#]+[A-Za-z0-9-_]+/g); 
}; 

string.findHashTags() 
// returns ["#hash1234", "#sweetthing", "#something_notimportant"] 

的模式是完全一样的。

+1

它也可以在没有括号的情况下工作。 – nnnnnn

+1

谢谢,很好。 –

+0

不客气。 +1,对于发布几乎相同的答案感到抱歉,但是我在看到你之前就开始打字了,我想包括关于没有匹配时会发生什么的信息,所以当我看到你没有提到的时候我继续与我的... – nnnnnn

0

使用匹配。

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());​ 
相关问题