获取url中字符最后两个实例之间的子字符串

Get substring between two last instances of character in url

本文关键字:实例 两个 之间 字符串 url 字符 最后 获取      更新时间:2023-09-26

我有url看起来像这样:http://i1.ytimg.com/vi/BR0Y3MZ21bo/0.jpg。有人能帮我提取"ID"BR0Y3MZ21bo之间的最后两个斜杠在url?

你可以使用split(), split会给你字符串的数组被/和你想要的字符串是在数组的倒数第二个索引。

现场演示

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

试试这个:

 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

小提琴