Nishant Singhal
Nishant Singhal

Reputation: 21

How can i pass params in url like a path in javascript?

How can I get the params from the URL path as we do in Django? For example if the url is domain.dom/userid, then we need userid as a param in js and redirect to domain.dom. Is this possible in javascript?

Upvotes: 0

Views: 144

Answers (3)

Nishant Singhal
Nishant Singhal

Reputation: 21

This can be achieved by redirecting through the .htaccess file and further

var path = location.pathname; var arr = path.split("/"); var name = arr[arr.length-1];

Hence, with this, we can achieve the parameters through the domain path in javascript.

Upvotes: 0

Agustín Charry
Agustín Charry

Reputation: 16

If you need the current URL and params, this could help you

I'am considering that the userID param is the first param like:

url.com/123

where 123 is the userID

//Get current base URL
let base_url = window.location.origin;

//Get userID or first param
//Change number 3 if your param is in another position
let userId = window.location.href.split("/")[3];
alert(userId);

//Redirect to base URL
window.location.href = base_url;

Upvotes: 0

mplungjan
mplungjan

Reputation: 177684

Try this

let url =  new URL("https://domain.dom/freddy_user"); // new Url(location.href) 
const userid = url.pathname.slice(1);
url.pathname="index.html";
url.searchParams.set("userid",userid)
console.log(url); // location.replace(url)

Upvotes: 1

Related Questions