abu abu
abu abu

Reputation: 7022

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?

Upvotes: 2

Views: 5240

Answers (3)

engr.ukairo
engr.ukairo

Reputation: 68

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.

Upvotes: 1

r3dst0rm
r3dst0rm

Reputation: 1926

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"

Upvotes: 3

uday8486
uday8486

Reputation: 1393

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

Upvotes: 1

Related Questions