I have URL like http://localhost:3000/register. How can I get register segment inside return() in React.js?
3 Answers
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"
Comments
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.
3 Comments
k.tten
This is invalid Javascript
engr.ukairo
@catgirlkelly Can you explain why it's invalid? Console.log lastPart prints the last part of the URL to the console.
k.tten
You forgot the quotes around the URL :x