How to search for href ending with numbers using querySelectorAll ()

I am looking to get all elements that end in a number. So, for example, we have <a>with this href.

href="artist.php?id=8932

Now I can get all occurrences of href with:

document.querySelectorAll("[href^='artist.php?id=']")

However, it also gives me results such as

artist.php?id=8932#comments

So, I want so that I can only get hrefs ending with a number in an array. I would not want to first create an array with all the results, and then clear #extras and remove duplicates.

Please note that I will not and will not use jQuery.

+4
source share
3 answers

querySelectorAll regexp, , href css. hrefs, , .filter .match.

let links = [...document.querySelectorAll("[href^='artist.php?id=']")].filter(a => a.href.match(/\d+$/));
console.log(links);
<a href="artist.php?id=123"></a>
<a href="artist1.php?id=123"></a>
<a href="artist.php?id=123#comment"></a>
<a href="artist.php?id=abc"></a>
<a href="artist.php?id=abc123"></a>
Hide result
+1

, , .

<a href="artist.php?id=1992">xxxx</a>

var v= document.querySelectorAll("[href^='artist.php?id=']")[0]
console.log(v.href);

output is :    
http://localhost:63342/artist.php?id=1992
0

While there is no way to include only those that end nearby, there is a way to filter output links ending in comments.

An example in a script.

const ids = document.querySelectorAll("[href^='artist.php?id=']:not([href$=comments])");



console.log(ids);
<a href="artist.php?id=8932#comments">
<a href="artist.php?id=007">
Run codeHide result
0
source

Source: https://habr.com/ru/post/1694117/


All Articles