简体   繁体   English

获取页面上与URL字符串匹配的所有链接

[英]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: 我目前正在使用此代码(以及Mootools)来构建#subnav div中包含特定网址字符串的所有锚点的数组:

$('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 . 问题是,如果我正在寻找work.aspx?subsection=24&project=1 ,它将匹配具有work.aspx?subsection=24&project=15 URL的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. 该正则表达式将匹配project = 1,然后是&或字符串的末尾。 It uses MooTool's (or the native browser's) Array.filter to remove all non-matches. 它使用MooTool(或本机浏览器)的Array.filter删除所有不匹配项。 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重定向更优雅地处理...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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