Adam
Adam

Reputation: 1

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

For example I've got the simple code:

<ul class="list">
  <li><a href="http://www.aaa.com/bbb/ccc/file01.pdf">Download file 01</a></li>
  <li><a href="http://www.bbb.com/ccc/ddd/file02.pdf">Download file 02</a></li>
</ul>

and I wish to store in variables only the file names: file01.pdf and file02.pdf, how can I cut them?

Many thanks for the help.

Cheers.

Upvotes: 0

Views: 630

Answers (6)

Alex Barrett
Alex Barrett

Reputation: 16475

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'].

Upvotes: 0

bobince
bobince

Reputation: 536577

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

Upvotes: 4

Mic
Mic

Reputation: 25164

Here another way:

var arr = [];
$("ul.list li a").each (function(){
    arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});

Upvotes: 0

rahul
rahul

Reputation: 187090

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 ) )
    });
});

Upvotes: 5

Pier Luigi
Pier Luigi

Reputation: 7871

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);
});

Upvotes: 0

Mark Bell
Mark Bell

Reputation: 29785

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]
}

Upvotes: 1

Related Questions