Use the . substring() method to get the access the string after last slash.
Using lastIndexOf and substring : var str = "foo/bar/test. html"; var n = str. lastIndexOf('/'); var result = str. substring(n + 1);
length function. Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.
The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).
At least three ways:
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
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.
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.
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.
Try this:
const url = "files/images/gallery/image.jpg";
console.log(url.split("/").pop());
var str = "foo/bar/test.html";
var lastSlash = str.lastIndexOf("/");
alert(str.substring(lastSlash+1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With