简体   繁体   中英

Displaying the filename of a HREF in Javascript

I have a page with a download button like this:

<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>

Below, I want (text) to automatically display "filename.pdf" (rather than having to do this by hand hundreds of times).

I found the script below that displays the filename of the PAGE but I want it to display the FILENAME of a HREF I've used on the actual page.

Any help is much appreciated.

<script type="text/javascript">

var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment);

</script>

Thanks in advance!

Not sure where you want the "text" to display... so I put it in a div

<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>


<div id="result">
</div>

The big change, is to get all the "a" tags, using getElementsByTagName... and then iterating over the list, and then you can use the string split, and pop off the last segment before appending it to a destination.

var input = document.getElementsByTagName('a');
for(i = 0;i < input.length; i++)
{
    var segment_str = input[i].href;
    var segment_array = segment_str.split( '/' );
    var last_segment = segment_array.pop();
    document.getElementById("result").innerText += last_segment; 
}

Maybe this will help.

<div id=download1></div>

<script>
var filename = 'example.pdf';
$('#download1').html('<a href="http://www.example.nl/' + filename + '">' + filename + '</a>');
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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