Method to capture trex of a URL with Javascript

Asked

Viewed 118 times

0

I have a URL, https://meusite.com/q6uzeyln32td/naoquero.html, and I need to 'cut' the code between the bars (q6uzeyln32td) for a variable. I have tried the split() method with the following code:

var mainURL = window.location.href;
mainURL = mainURL.split('.com/');

However, it always returns an array like this:

Array [ "https://site", "q6uzeyln32td/naoquero.html" ]

The value I want is with others I don’t want.

  • 1

    There are numerous ways to do this. I wouldn’t say that the split be the best solution, but the best way would also depend on the restrictions you may have.

  • 1

    A solution still with the split would use only the / and take position 3 of the generated array.

  • 1

    You have can use window.location.pathname, in place of window.location.href and will already have the URL without the protocol and domain.

  • Great, I modified and worked normally, without having to make the request twice... Thanks @tvdias

  • When you can (if I’m not mistaken for the least time), add a reply and mark it as accepted.

  • AP used the question itself to answer. The question was reverted to the first version and the answer was put as wiki.

  • window.location.pathname.split('/')[1]

Show 2 more comments

2 answers

3

Just use the class URL, access the value of path and split into bar:

// const url = window.location;
const url = new URL('https://meusite.com/q6uzeyln32td/naoquero.html')
const segments = url.pathname.split('/')

console.log(segments[1]);

0

The author of the question mistakenly put this answer in the question:

After posting, I read the code and thought about making another Split(), so it worked:

var mainURL = window.location.href;
mainURL = mainURL.split('.com/');
mainURL = mainURL[1];
mainURL = mainURL.split('/');
mainURL = mainURL[0];

I don’t know if it’s the most efficient, probably not, but there it is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.