What is the best way to cut the file name from 'href' attribute of an 'a' element using jQuery?

后端 未结 6 532
傲寒
傲寒 2021-01-16 19:32

For example I\'ve got the simple code:

相关标签:
6条回答
  • 2021-01-16 20:13
    var fileNames = new Array();
    
    $('.list a').each(function(i, item){
        fileNames.push(this.href.substring(this.href.lastIndexOf('/') + 1))
    });
    

    This will give you an array of all the filenames, then:

    for(var x=0; x<fileNames.length; x++)
    {
        // Do something with fileNames[x]
    }
    
    0 讨论(0)
  • 2021-01-16 20:15

    use

    lastIndexof and substring

    Give anchor tag an id

    var elem = document.getElementById ( "anch1" );
    
    elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );
    

    Using jQuery

    $(function() {
        $("ul.list li a").each ( function() {
            alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
        });
    });
    
    0 讨论(0)
  • 2021-01-16 20:15

    Here another way:

    var arr = [];
    $("ul.list li a").each (function(){
        arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
    });
    
    0 讨论(0)
  • 2021-01-16 20:22

    Though you don't have them in this case, in general you would want to strip off the ?search and #hash parts before looking for the last slash to get the file's leafname.

    This is very easy using the built-in properties of the link object like pathname instead of processing the complete href:

    var a= document.getElementById('link1');    // or however you decide to reference it
    var filename= a.pathname.split('/').pop();  // get last segment of path
    
    0 讨论(0)
  • 2021-01-16 20:22
    var files = $('a[href]').map(function() {
        return this.pathname.match(/[^\/]*$/)[0];
    });
    

    a[href] will exclude anchors without hrefs (such as named anchors), and pathname will remove query strings and fragments (?query=string and #fragment).

    After this, files will contain an array of filenames: ['file01.pdf', 'file02.pdf'].

    0 讨论(0)
  • 2021-01-16 20:35
    var myFilename = [];
    $("ul.list li a").each(function() {
          var href = $(this).attr('href'); 
          var idx = $(this).attr('href').lastIndexOf('/');
          myFilename.push((idx >= 0) ? href.substring(idx+1) : href);
    });
    
    0 讨论(0)
提交回复
热议问题