Search code examples
javascripthtmljqueryuserscripts

Getting the last segment of an URL


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);

Solution

  • 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"