gpt4 book ai didi

jquery - 返回匹配子字符串的数组

转载 作者:行者123 更新时间:2023-12-01 02:59:19 24 4
gpt4 key购买 nike

我有这个漂亮的函数,但我需要自定义它以仅返回与正则表达式匹配的项目数组。所以结果将是 #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());

最佳答案

.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) || [];
}

关于jquery - 返回匹配子字符串的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13243942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com