Reputation: 1211
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
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
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
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
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