Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last part of a string in JavaScript?

Tags:

javascript

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?

like image 586
Jacob Avatar asked May 29 '11 01:05

Jacob


People also ask

How do you find the last element of a string?

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)".

How do I get the last 5 characters of a string?

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.

How do I get the last 3 characters of a string?

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.

How do you find the last two elements of a string?

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.


2 Answers

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]);   } 
like image 27
Niklas Avatar answered Oct 18 '22 03:10

Niklas


One way:

var lastPart = url.split("/").pop(); 
like image 179
Ates Goral Avatar answered Oct 18 '22 03:10

Ates Goral