2

I have URL like http://localhost:3000/register. How can I get register segment inside return() in React.js?

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

This is invalid Javascript
@catgirlkelly Can you explain why it's invalid? Console.log lastPart prints the last part of the URL to the console.
You forgot the quotes around the URL :x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.