0

How to get string after second slash in url?

I have this link :

https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL

I want to get this :

JiTY6s0ejuDAG3LNJq3YPEmL

I mean, after :

https://en.exemple.com/invite/
luiscla27
  • 4,956
  • 37
  • 49
Asfar
  • 25
  • 8

4 Answers4

1

Many ways to do this, for example this (if you're sure your URL always is of that form):

const url = 'https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL';
const identifier = url.match(/invite\/(.*)$/)[1];

console.log(identifier);

No need for jQuery for this.

PS: next time please show what you attempted.

Jeto
  • 14,596
  • 2
  • 32
  • 46
1

let url = "https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL";
let str = url.substring(url.lastIndexOf("/")+1);

console.log(str);
vicbyte
  • 3,690
  • 1
  • 11
  • 20
1

You can use regular expressions, you may read more about them here. The following solution works for any URL:

function getLastURLPart(url) {
    var part = url.match(/.*\/(.+)/);
    if(!part) {
        return null;
    }
    return part[1];
}

then you can just use it like this:

var url = "https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL";
console.log(getLastURLPart(url));

Also you can directly use the regExp like this:

var url = "https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL";
alert(url.match(/.*\/(.+)/)[1]);
luiscla27
  • 4,956
  • 37
  • 49
0

You can do it like this, which gives you access to all the parts of the url:

const url = 'https://en.exemple.com/invite/JiTY6s0ejuDAG3LNJq3YPEmL';

const urlParts = url.split('/').filter(Boolean); // <-- split by '/' and remove empty parts

console.log(urlParts);
console.log(urlParts[3]); // <-- what you want
Baboo
  • 4,008
  • 3
  • 18
  • 33