heisenberg
heisenberg

Reputation: 51

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

How to get a link using jQuery which has an exact pattern at the end of it? E, g, I have the following code:

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

So, the links could be: https://my_site.com/XX-1635, https://my_site.com/XX-7432, https://my_site.com/XX-6426 and so on.

In other words, it could be any 4 digits after the "XX-".

Upvotes: 1

Views: 74

Answers (4)

Redu
Redu

Reputation: 26161

No need for jQuery at all. Simply can be accomplished by pure JS in a single line. It's probably multiple times faster too.

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

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can use filter() with attribute starts with selector.

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));

Upvotes: 1

user4278933
user4278933

Reputation:

Where is the source of your data?

I suspect the data you are trying to read is encoded for safe transport. This is where the space is converted to to %20 for example.

If true, you need convert your source data using encodeURIComponent(), then apply your find.

This might work (though my usage of search is weak). I have not tested this code but should give you an idea on direction...

// 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

Upvotes: 0

rrk
rrk

Reputation: 15846

You can use filter() for this.

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

Upvotes: 1

Related Questions