Getting the last segment of an URL

Viewed 125

Let's say that this is my URL/Link that i have written in an input

https://www.instagram.com/p/CBt-W4jHZjH/

How can I get the "CBt-W4jHZjH" part?

var link = ?????

var a = link.val().trim();
var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
var validation = regex.test(a);
2 Answers

Many ways to do it. One way is to look for / any character but / ending with / end of line.

var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.match(/\/([^\/]+)\/?$/)[1])

Could be done with split. The filter removes the empty string caused by the trailing /.

var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.split('/').filter(x=>x).pop());

https://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"

Related