0

I have a script that does some calculations and returns a Google Maps direction drawn on a map with the API.

I will keep my question easy and use this example:

var a;
var b;
var c;
function DoMath(){
  //random number 1-20 for example
  a = random(1,20);
  b = random(1,20); 
  c = a + b;
}

So now the function makes a sum with random numbers. I want it like this:

When the users types after the site url /5/14 that the JavaScript sets a to 5 and b to 14 and uses those numbers instead of randoms. I also want the script to use randoms when there is nothing given in url.

Questions:

  • How do I read url?
  • How do I set the var to the url value?
  • How can I make it so you could give only a or b or both in the url?

1 Answer 1

3

You can use the

document.location.pathname

This variable returns the url's pathname.

Example:

/questions/23874345/javascript-functions-by-url

Now you need to split this with '/'

var args = document.location.pathname.split('/');

Now you can use the 'args' array. (Note: args[0] returns "")

var a = parseInt(args[1]);
var b = parseInt(args[2]);

If you want to make sure no extra data is entered in the url use:

if (args.length > DESIREDVARIABLES) alert('Too many data');

Something like that =)

Good Luck!

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

4 Comments

Thank you for your answer. I'm using codeigniter as framework, how is it possible to read whats behind the first / if the framework routes to a 401 error?
Well, sorry but i don't know codeigniter, and this question is javascript related, but in PHP you can get the server name (the thing behind the first /) via this: $_SERVER['SERVER_NAME'] this will return 'stackoverflow.com' or 'www.stackoverflow.com' in this case.
Is there a way to do it like this: url.com?rest=1&cafe=2&query=London how can i read that?
@Onovar - If your server is not equipped to leave the pathname alone, then you can put the arguments in the query string: /questions?arg1=5&arg2=14 and then parse those out of the URL.

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.