如何使用jquery从链接中取出文件名

时间:2010-10-17 09:55:10

标签: jquery

我正在使用Jquery。

我的html中有以下链接

<a class="load-fragment" href="/english/india/index.aspx"><span>Overview</span></a>
<a class="load-fragment" href="/english/india/guide.aspx"><span>Guide</span></a>

我正试图从(href =“/ english / india / index.aspx”,href =“/ english”中取出“索引”和“指南” /india/guide.aspx“)来自上面链接的文本,它们将存储在一个变量中供进一步使用,因为上面给出了很多链接,所以会有循环。

请建议使用Jquery!

谢谢!

4 个答案:

答案 0 :(得分:4)

您可以使用这样的正则表达式:

$(".load-fragment").each(function() {
   var fileName = $(this).attr("href").match(/^\/.*\/([^\/]+).aspx$/)[1];
   //store fileName where needed
});​

You can test it out here,或者如果你想要一组数组使用.map()

var files = $(".load-fragment").map(function() {
              return $(this).attr("href").match(/^\/.*\/([^\/]+).aspx$/)[1];
            }).get();​

答案 1 :(得分:1)

这个怎么样?

var filenames = $('.load-fragment').map(function() {
   var href =    $(this).attr('href'); 
   var lastSlash = href.lastIndexOf('/');
   var new_href = href.substring(0, lastSlash);
   return href.substring(lastSlash + 1, href.lastIndexOf('.')));
}).get();​

答案 2 :(得分:0)

我会做这样的事情:

var files = [];
$('a.load-fragment').each(function(){
    var loc = $(this).attr('href');
    loc = loc.substring(loc.lastIndexOf('/')+1);
    files.push(loc);
});
alert(files);

然后,您可以从文件数组files[0], files[1]

访问每个文件

答案 3 :(得分:0)

Nick Craver的答案变种:

$(".load-fragment").each(function() {
   var fileName = this.href.split(/[/.]/).slice(-2,-1);
   //store fileName where needed
});

但是,这假设链接始终具有您显示的格式。正则表达式可能更安全,因为它也是验证。

"/english/india/index.aspx".split(/[/.]/)
// returns: ["", "english", "india", "index", "aspx"]

["", "english", "india", "index", "aspx"].slice(-2, -1)
// returns "index"