'How to get URL segment in react.js
I have URL like http://localhost:3000/register
. How can I get register
segment inside return()
in React.js
?
Solution 1:[1]
Something along the lines would also work, in case you don't always want to have the last segment.
If you have the URL as string and want to parse it. Note: This won't work on IE11, but there are polyfills like: GitHub for URL polyfill (for more information please read up on MDN)
const url = new URL("http://localhost:3000/register");
const pathname = url.pathname; // contains "/register"
in case you are trying to access the URL using the window object, you get the pathname almost for free:
const pathname = window.location.pathname; // also contains: "/register"
Solution 2:[2]
Something like below:
const url = "http://localhost:3000/register";
const segment = url.substring(url.lastIndexOf('/') + 1);
This will give always last segment. Let's say if your URL is http://localhost:3000/user/John.
It would give segment as John
Solution 3:[3]
You can use the following:
const fullUrl = "http://localhost:3000/register"; //use this to get the complete url => window.location.href;
const lastPart = fullUrl.split("/").pop(); //this will give you register.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | r3dst0rm |
Solution 2 | uday8486 |
Solution 3 | hittingonme |