简体   繁体   中英

Getting all links on a page that match a url string

I'm currently using this code (along with Mootools) to build an array of all anchors in the #subnav div that contain a specific url string:

$('subnav').getElements('a[href*=/'+href+']')

Problem is if I'm looking for work.aspx?subsection=24&project=1 that will match anchors with a URL of work.aspx?subsection=24&project=15 .

How can I prevent that from happening?

The only solution I can think of is to use regexes; something like this:

$('subnav').getElements('a').filter(function (element, index) {
    return /work\.aspx\?subsection=24&project=1(?:$|&)/.test(element.href);
});

That regex will match project=1 and then either a & or the end of the string. It uses MooTool's (or the native browser's) Array.filter to remove all non-matches. It isn't the most elegant solution, especially if you are using this dynamically, since then you'd have to write some code to create a new regex.

Going to answer my own question. It was as simple as changing the * to a $ .

$('subnav').getElements('a[href$=/'+href+']')

听起来应该通过301或302重定向更优雅地处理...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM