0

I have a button as follows:

<button class="btn btn-danger delete" data-type="GET" data-url="/js/jQuery-File-Upload-master/server/cf/Upload.cfc?method=init&amp;file=quote_3-39Sussex.pdf">
    <i class="glyphicon glyphicon-trash"></i>
    <span>Delete</span>
</button>

I need some jquery to isolate and return only the filename from the data-url attribute, i.e. "quote_3-39Sussex.pdf"

How would this be done?

Assuming a button click listener, I guess the beginnings would be something like:

var str = $(this).attr('data-url');
var file = str.join?(something)?. I don't know how to proceed
user460114
  • 1,848
  • 3
  • 31
  • 54

3 Answers3

1

You can split the string like this :

var file = str.split("=")[2]

and you will have the file

here we cut str each time we find = and I just take the last one to get the file name

assuming your url is always like the one in the example

var str = $(".delete").attr('data-url');
var file = str.split("=")[2]
console.log(file)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-danger delete" data-type="GET" data-url="/js/jQuery-File-Upload-master/server/cf/Upload.cfc?method=init&amp;file=quote_3-39Sussex.pdf">
    <i class="glyphicon glyphicon-trash"></i>
    <span>Delete</span>
</button>
Jerome
  • 1,162
  • 2
  • 16
  • 32
1

If the "file" parameter is always supposed to be the last one, maybe you could try :

var url_parts = str.split('=');
var file = url_parts[url_parts.length - 1];

Hope this helps !

Lucas Delobelle
  • 424
  • 2
  • 6
0

It is better to use the jQuery data method for accessing the data-url attribute. And then to get the URL part, use split and pop:

var str = $(this).data('url');
var file = str.split('file=').pop();

This assumes that the file parameter is present and is the last one in the URL. If not, then this regular expression can be used, with an added test that there was a match:

var str = $(this).data('url');
var m = str.match(/[&?]file=([^&#]*)/);
var file = m ? m.pop() : null;

The generic question on how to get parameter values from an arbitrary URL has been answered here and provides more elaborate and robust answers.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286