Phil
Phil

Reputation: 1849

Get substring between two last instances of character in url

I have urls which look like this :http://i1.ytimg.com/vi/BR0Y3MZ21bo/0.jpg. Can someone help me extract the "ID" BR0Y3MZ21bo between the last two slashes in the url?

Upvotes: 2

Views: 1695

Answers (2)

Jai
Jai

Reputation: 74738

Try this:

 var url = 'http://i1.ytimg.com/vi/BR0Y3MZ21bo/0.jpg'; // window.location.href;
 var page = url.substr(0, url.lastIndexOf('/')); // output -> http://i1.ytimg.com/vi/BR0Y3MZ21bo
 var str = page.substr(page.lastIndexOf('/')+1); // output -> BR0Y3MZ21bo
 alert(str); // BR0Y3MZ21bo

FIDDLE

Upvotes: 0

Adil
Adil

Reputation: 148180

You can use split(), split will give you array of string being separated by / and your desired string is at second last index of array.

Live Demo

arr = url.split('/');
arr[arr.length-2];

Upvotes: 6

Related Questions