假设这是我在输入框中编写的URL /链接
https://www.instagram.com/p/CBt-W4jHZjH/
我该如何获取“CBt-W4jHZjH”部分?
var link = ?????
var a = link.val().trim();
var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
var validation = regex.test(a);
假设这是我在输入框中编写的URL /链接
https://www.instagram.com/p/CBt-W4jHZjH/
我该如何获取“CBt-W4jHZjH”部分?
var link = ?????
var a = link.val().trim();
var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
var validation = regex.test(a);
var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.match(/\/([^\/]+)\/?$/)[1])
/
引起的空字符串。
var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.split('/').filter(x=>x).pop());
pathname
属性,使用 URL API 真的值得吗?为什么不直接将 match()
应用于 URL 字符串呢?而且在方括号内部不需要转义斜杠,它应该可以正常工作。 - Yevhen Horbunkovconst [,hash] = .match(/\/([^/]+)\/$/)
), 但后来变懒了,就在OP下面留了一个丑陋的评论 ;) - Yevhen Horbunkovhttps://developer.mozilla.org/en-US/docs/Web/API/URL
const getLastPath = (url) => {
url = new URL(url);
const pathname = url.pathname;
const paths = pathname.split("/");
return paths.pop() || paths.pop();
}
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH/")); // "CBt-W4jHZjH"
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH")); // "CBt-W4jHZjH"
'https://www.instagram.com/p/CBt-W4jHZjH/'.match(/\/([^/]+)\/$/)[1]
- Yevhen Horbunkov