193

I am already trying for over an hour and cant figure out the right way to do it, although it is probably pretty easy:

I have something like this : foo/bar/test.html

I would like to use jQuery to extract everything after the last /. In the example above the output would be test.html.

I guess it can be done using substr and indexOf(), but I cant find a working solution.

Jhourlad Estrella
  • 3,545
  • 4
  • 37
  • 66
r0skar
  • 8,338
  • 14
  • 50
  • 69

12 Answers12

357

At least three ways:

A regular expression:

var result = /[^/]*$/.exec("foo/bar/test.html")[0];

...which says "grab the series of characters not containing a slash" ([^/]*) at the end of the string ($). Then it grabs the matched characters from the returned match object by indexing into it ([0]); in a match object, the first entry is the whole matched string. No need for capture groups.

Live example

Using lastIndexOf and substring:

var str = "foo/bar/test.html";
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);

lastIndexOf does what it sounds like it does: It finds the index of the last occurrence of a character (well, string) in a string, returning -1 if not found. Nine times out of ten you probably want to check that return value (if (n !== -1)), but in the above since we're adding 1 to it and calling substring, we'd end up doing str.substring(0) which just returns the string.

Using Array#split

Sudhir and Tom Walters have this covered here and here, but just for completeness:

var parts = "foo/bar/test.html".split("/");
var result = parts[parts.length - 1]; // Or parts.pop();

split splits up a string using the given delimiter, returning an array.

The lastIndexOf / substring solution is probably the most efficient (although one always has to be careful saying anything about JavaScript and performance, since the engines vary so radically from each other), but unless you're doing this thousands of times in a loop, it doesn't matter and I'd strive for clarity of code.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    How would you adapt this to return the string before final slash? (I.e return the name of the parent folder) – wbadart Jun 22 '15 at 00:35
67

Try this:

const url = "files/images/gallery/image.jpg";

console.log(url.split("/").pop());
Patrycja Petryk
  • 681
  • 5
  • 3
36

You don't need jQuery, and there are a bunch of ways to do it, for example:

var parts = myString.split('/');
var answer = parts[parts.length - 1];

Where myString contains your string.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
  • 3
    +1 (for working) pointing out that jQuery is not the be-all end-all solution for javascript issues. – Andrew Jackman Dec 04 '11 at 16:05
  • 1
    This is a buggy solution, try what happens if you add the slash to the slug? It returns 0. And what happens there is no slug? - returns NaN! wtf? bad code – Donatas Cereska Feb 10 '14 at 09:47
  • 2
    1) The question was related to an input which wasn't null 2) The input was related to inputs ending in file-names (no slashes) 3) The accepted answer is indeed a much better solution, hence the numerous up votes 4) You're welcome to add your own solution – Tom Walters Feb 11 '14 at 10:50
21
var str = "foo/bar/test.html";
var lastSlash = str.lastIndexOf("/");
alert(str.substring(lastSlash+1));
kasdega
  • 18,396
  • 12
  • 45
  • 89
10

Try;

var str = "foo/bar/test.html";
var tmp = str.split("/");
alert(tmp.pop());
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
7

When I know the string is going to be reasonably short then I use the following one liner... (remember to escape backslashes)

// if str is C:\windows\file system\path\picture name.jpg
alert( str.split('\\').pop() );

alert pops up with picture name.jpg

DaveAlger
  • 2,376
  • 25
  • 24
4

This might be an old thread but I stumbled upon it and found a much nicer option after a while:

var str = "foo/bar/test.html";
alert(str.split('/').pop());
// output will be: test.html
JCoding
  • 109
  • 9
2
String path ="AnyDirectory/subFolder/last.htm";
int pos = path.lastIndexOf("/") + 1;

path.substring(pos, path.length()-pos) ;

Now you have the last.htm in the path string.

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
2

light weigh

string.substring(start,end)

where

start = Required. The position where to start the extraction. First character is at index 0`.

end = Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string.

    var string = "var1/var2/var3";

    start   = string.lastIndexOf('/');  //console.log(start); o/p:- 9
    end     = string.length;            //console.log(end);   o/p:- 14

    var string_before_last_slash = string.substring(0, start);
    console.log(string_before_last_slash);//o/p:- var1/var2

    var string_after_last_slash = string.substring(start+1, end);
    console.log(string_after_last_slash);//o/p:- var3

OR

    var string_after_last_slash = string.substring(start+1);
    console.log(string_after_last_slash);//o/p:- var3
A J
  • 3,970
  • 14
  • 38
  • 53
Shailesh Sonare
  • 2,791
  • 1
  • 18
  • 14
1

Jquery:

var afterDot = value.substr(value.lastIndexOf('_') + 1);

Javascript:

var myString = 'asd/f/df/xc/asd/test.jpg'
var parts    = myString.split('/');
var answer   = parts[parts.length - 1];
console.log(answer);

Replace '_' || '/' to your own need

SMPLYJR
  • 854
  • 1
  • 11
  • 23
1

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }
1

You can try this one too:

var str = 'foo/bar/test.html';
var output = str.split('/');
var lastElement = output[output.length-1];
console.log(lastElement); //test.html

Hope this could help ~RDaksh

Rahul Daksh
  • 212
  • 1
  • 7