如何使用jQuery打开一个链接,它的末尾有一个确切的模式

How to open a link using jQuery which has an exact pattern at the end of it?

本文关键字:有一个 模式 链接 一个 jQuery 何使用      更新时间:2024-04-17

如何使用jQuery获得一个末尾有确切模式的链接?E、 g,我有以下代码:

return $(document).find("a[href='https://my_site.com/XX-' + /'d(?='d{4})/g, "*"]");

因此,链接可能是:https://my_site.com/XX-1635,https://my_site.com/XX-7432,https://my_site.com/XX-6426等等

换句话说,它可以是"XX-"之后的任意4位数字。

您可以使用filter()

reg = /https:'/'/my_site.com'/XX-'d{4}$/g;
elements = $(document)
   .find("a")
   .filter(function(){
       return reg.test(this.href);
   });
return elements;

您可以使用属性以选择器开头的filter()

var regex = /XX-'d{4}$/; // Exact four digits after XX-
var anchors = $(document.body)
    .find('a[href^="https://my_site.com/XX-"]')
    .filter(() => regex.test(this.href));

数据的来源在哪里?

我怀疑你试图读取的数据是为了安全运输而编码的。例如,这就是将空间转换为%20的位置。

如果为true,则需要使用encodeURIComponent()转换源数据,然后应用您的查找结果。

这可能会起作用(尽管我对搜索的使用很弱)。我还没有测试这个代码,但应该给你一个方向的想法。。。

// Collate all href from the document and store in array links
var links=[];
$(document).find("a").each(
function()
{
 links.push( encodeURIComponent( $(this).prop("href") ) );
});
// Loop thru array links, perform your search on each element,
// store result in array results
var results=[];
results=links.filter(function(item){
    return item.search('/'d(?='d{4})/g');
});
console.log( results );

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

根本不需要jQuery。纯JS可以在一行中简单地完成。它可能也快了好几倍。

var as = document.getElementsByTagName("a"),
   ael = Array.prototype.filter.call(as, e => /XX-'d{4}$/g.test(e.href));