Get last slash url javascript
My url will look like this: Show http://www.example.com/category/action How can I get the word "action". This last part of the url (after the last forward slash "/") will be different each time. So whether its "action" or "adventure", etc. how can I always get the word after the last closing forward slash?
Ates Goral 134k26 gold badges134 silver badges189 bronze badges asked May 29, 2011 at 1:22
1 One way:
answered May 29, 2011 at 1:24
Ates GoralAtes Goral 134k26 gold badges134 silver badges189 bronze badges 1 Assuming there is no trailing slash, you could get it like this:
However, if there can be a trailing slash, you could use the following:
answered May 29, 2011 at 1:25
NiklasNiklas 29.5k5 gold badges48 silver badges70 bronze badges 1
Though if your URL could contain a query or fragment, you might want to do
first to make sure you have a URL with the path at the end. answered May 29, 2011 at 1:28
Mike SamuelMike Samuel 115k30 gold badges211 silver badges241 bronze badges Or the regex way:
OR
answered May 29, 2011 at 1:53
JonathonJonathon 2,4885 gold badges27 silver badges48 bronze badges Well, the first thing I can think of is using the
Since everyone suggested the split function, a second way wood be this:
The regexp is just a stub to get the idea. Basically you get every words in the url. l = http,www,example,com,category,action get the last one. answered May 29, 2011 at 1:28
dierredierre 7,06012 gold badges72 silver badges117 bronze badges View Discussion Improve Article Save Article View Discussion Improve Article Save Article The task is to get the string after a specific character(‘/’). Here are few of the mostly used techniques discussed. We are going to use
JavaScript.
Example 1: This example using the approach discussed above.
Output: Approach 2:
Example 2: This example using the approach discussed above.
Output: How do you find the last slash in a string?First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.
How do I find the last path of a URL?We identify the index of the last / in the path, calling lastIndexOf('/') on the thePath string. Then we pass that to the substring() method we call on the same thePath string. This will return a new string that starts from the position of the last / , + 1 (otherwise we'd also get the / back).
How do you extract a substring after the last occurrence of the delimiter in JavaScript?Using lastIndexOf and substring :
var str = "foo/bar/test. html"; var n = str. lastIndexOf('/'); var result = str. substring(n + 1);
How do you split a slash in JavaScript?JavaScript split by slash using regular expression
js let mString = 'millie/bobby/brown'; let splits = mString. split(/[\\\/]/); console. log(splits);
|