0
url("http://localhost/garg/public/img/slides/9234385e2911fd07346cae2d78548d20.jpg")

I would like to get the 9234385e2911fd07346cae2d78548d20.jpg part.

I've tried to slice my way through, but it doesn't really work.

string.slice(0,-2);
string.slice(0,5);
....

But it's not very efficient. How can I do it elsewhy?

John
  • 2,900
  • 8
  • 36
  • 65
  • 2
    Here's an idea: search for the last occurrence of `/` and grab anything that follows. Although of course this won't work for any random URL. You can search with [`lastIndexOf`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). – Jon Jun 13 '14 at 09:43
  • string.split("/").pop(); – mplungjan Jun 13 '14 at 11:37

4 Answers4

2

You can consider using this approach using REGEX:

var fullPath = "http://localhost/garg/public/img/slides/9234385e2911fd07346cae2d78548d20.jpg";
var filename = fullPath.replace(/^.*[\\\/]/, '');

alert (filename);

This is however a simpler approach

 var fullPath = "http://localhost/garg/public/img/slides/9234385e2911fd07346cae2d78548d20.jpg";
 var filename = fullPath​​​​​​​.split('/').pop();
 alert (filename);
ngrashia
  • 9,869
  • 5
  • 43
  • 58
1

Use lastIndexOf() : find last occurrence of the passed parameter.

Fiddle Demo

str.substr(str.lastIndexOf ("/") + 1);
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
1

you can use it this way :

$("input[name='attachment']").change(function() {
      console.log('fileName');
    var fileName = $(this).val().split('\\').pop();
    console.log(fileName);
});

Fiddle : http://jsfiddle.net/nSf7w/157/

Pranav
  • 666
  • 3
  • 7
0

Use:

var match = "http://localhost/garg/public/img/slides/9234385e2911fd07346cae2d78548d20.jpg".match(/[^/]*$/);
var filename = match ? match[0] : '';
xdazz
  • 158,678
  • 38
  • 247
  • 274