0

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?

6
  • 1
    location.pathname - is that what you mean? Commented Aug 7, 2020 at 19:22
  • it will return the path of the current URL but won't redirect to the desired page like index.html or any other page, like if we go to the above mentioned url then it will return object not found rather than the path name. @mplungjan Commented Aug 7, 2020 at 19:27
  • 1
    It is completely unclear what you want to achieve. Please elaborate what your expected behaviour is with relevant and detailed input and expected output. Do you mean location.replace("someurl") Commented Aug 7, 2020 at 19:40
  • I want the user to go to the URL: domain.dom/userid I want it to go to domain.dom/index.html with the parameter userid Commented Aug 7, 2020 at 19:42
  • @NishantSinghal do you mean something like : github.com/rcs/route-parser ? Commented Aug 7, 2020 at 19:46

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

6 Comments

on which page should i write this code so that object not found error is not shown
You put this in the head of the page that receives the userid- you uncomment my comments and remove the test strings
but it doesn't recieve the request with the error object not found
I have no idea what you mean
I have no idea how your server works. You were the one giving very little info on how you pass the userid. I just came up with something to not confuse userid=userid - it seems you need to play with htaccess instead of JavaScript
|
0

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;

Comments

0

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.

Comments

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.