My url will look like this:
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?
If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.
To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original string.
Assuming there is no trailing slash, you could get it like this:
var url = "http://www.mysite.com/category/action"; var parts = url.split("/"); alert(parts[parts.length-1]);
However, if there can be a trailing slash, you could use the following:
var url = "http://www.mysite.com/category/action/"; var parts = url.split("/"); if (parts[parts.length-1].length==0){ alert(parts[parts.length-2]); }else{ alert(parts[parts.length-1]); }
One way:
var lastPart = url.split("/").pop();
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