For example I\'ve got the simple code:
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]
}
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 ) )
});
});
Here another way:
var arr = [];
$("ul.list li a").each (function(){
arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});
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
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']
.
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);
});