Home > Mobile >  How to get url from url in React and pass to a state
How to get url from url in React and pass to a state

Time:11-18

So I want to do an invite link in React from example: /invite/e04d2h, and then a component it will load, so that will have an input to enter the playing code, and what I want to do is get that data in this case: e04d2he from url and put to the input (state) automatically so he just can click enter to enter/play it.

CodePudding user response:

This snippet will give you the code:

const playingCode = /[^/]*$/.exec(window.location.href)[0];

CodePudding user response:

If you have URL like /invite/e04d2h as you mentioned in your question, you might try this as well.

const getCode = (url) => {
    const link = url;
    let splitedLink = link.split('/');
    return splitedLink[splitedLink.length-1]; // e04d2h
}

getCode("/invite/e04d2h");

This will split the URL by / and get the last one.

  • Related