-1

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
  • 3,127
  • 26
  • 39
Asfar
  • 5
  • 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,091
  • 2
  • 30
  • 43
1

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

console.log(str);
vicbyte
  • 3,500
  • 1
  • 8
  • 18
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
  • 3,127
  • 26
  • 39
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
  • 3,326
  • 2
  • 15
  • 26