Funereal
Funereal

Reputation: 673

How to extract last value in the URL before the last / separator using JQuery

I have this URL:

http://test.com/en/country/city

Im using lastIndexOf to obtain "city" but I want to obtain "country"

window.location.href.substring(window.location.href.lastIndexOf('/') + 1);

Is this posible with lasIndexOf or there is another function available for this case?

Thank you in advance!

Upvotes: 0

Views: 108

Answers (6)

Mukund Gandlur
Mukund Gandlur

Reputation: 869

Try something like this.

var url = window.location.href;
var urlArray = url.split("/"); 

urlArray[urlArray.length-1] //City
urlArray[urlArray.length-2] //Country

Upvotes: 0

Jitendra Tiwari
Jitendra Tiwari

Reputation: 1691

Use split function to get second last value.

Try this

var url='http://test.com/en/country/city';

var splitArray=url.split('/');

alert(splitArray[splitArray.length-2]);

Upvotes: 1

Satej S
Satej S

Reputation: 2156

Is this posible with lastIndexOf?

Yes, it is possible.

Let's say

x="http://test.com/en/country/city"

We get the position of the last /

y=x.lastIndexOf("/");//26

We get the position of the second last /

z=x.lastIndexOf("/",y-1);//18

To extract the country, we now use substring as follows

x.substring(z+1,y)//country

Upvotes: 1

Sam Pettersson
Sam Pettersson

Reputation: 3217

You could do something like this:

var url = "http://test.com/en/country/city"
var urlParts = url.split("/")
urlParts[urlParts.length - 1] (which would equal to "city")
urlParts[urlParts.length - 2] (which would equal to "country")

Basically split on each occurence of "/" and pick the correct item from the returned array.

Upvotes: 1

Justinas
Justinas

Reputation: 43441

You can split your url by / and take needed element (first remove http:// part):

var str = 'http://test.com/en/country/city';

str = str.replace('http://', '');

var parts = str.split('/');
console.log(parts);

alert(parts[2]+', '+parts[3]);

Upvotes: 3

Dhara Parmar
Dhara Parmar

Reputation: 8101

Try:

var  fragment = "http://test.com/en/country/city";
var array_fragment = fragment.split('/');
var city = array_fragment[array_fragment.length - 1]
var country = array_fragment[array_fragment.length - 2]
alert(country)

Upvotes: 1

Related Questions