Adia
Adia

Reputation: 1211

How to extract from the second last value

From the following URL example:

google.com/sports/football/asia

How to extract from the second last forward slash, that is /football/asia using jQuery? I know the functions are substring and lastIndexOf(), but how to use them in this case?

Thanks in advance!

Upvotes: 0

Views: 242

Answers (4)

BenjaminRH
BenjaminRH

Reputation: 12172

Perhaps you meant RegEx? The correct regex for that would be: /\w+\/\w+$/i. You can use Javascript's match() method to get your content from the string:

var myContent = "google.com/sports/football/asia".match(/\w+\/\w+$/i);

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272056

You can use the String.lastIndexOf() function -- twice:

var str = "google.com/sports/football/asia";
var foo = str.substring(str.lastIndexOf("/", str.lastIndexOf("/") - 1));

A better solution would be to use the String.split() function followed by Array.slice() and Array.join() functions 1like so:

"google.com/sports/football/asia".split("/").slice(-2).join("/");

Upvotes: 3

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

var url = "google.com/sports/football/asia";
var arr = url.split('/'),
foo = arr[arr.length-2] + '/' + arr[arr.length-1];
console.log(foo);

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the split function and take the last 2 elements of the resulting array:

var url = 'google.com/sports/football/asia';
var parts = url.split('/');
if (parts.length > 1) {
    var result = parts[parts.length - 2] + '/' + parts[parts.length - 1];
    alert(result);
}

Upvotes: 2

Related Questions