0

How would you extract the URL parameters in javascript through a POST method?

For example: localhost:8080/file.html/a/30/b/40

a and b would be keys while 30 and 40 would be the values for those keys

Thanks in advance!

0

2 Answers 2

1

Did you mean GET?

file.html?a=30&b=40

From this URL, you can get the parameters as follows:

var param = {};
var s = window.location.search.substring(1).split('&');
for (var i = 0; i < s.length; ++i) {
    var parts = s[i].split('=');
    param[parts[0]] = parts[1];
}
console.log(param);



EDIT:

The URL you provided doesn't have to do anything with POST, as far as I know, but if you can get it into a JavaScript variable, you can do this:

var url = "file.html/a/30/b/40";

var param = {};
var parts = url.split("/");
for (var i = 1; i < parts.length; i += 2) {
    param[parts[i]] = parts[i+1];
}
console.log(param);
Sign up to request clarification or add additional context in comments.

3 Comments

Aletheios, I mean POST. I'm trying to find a way to get the parameters from file.html/a/30/b/40
that works for that specific URL, but what about any arbitrary one in that same format? I'm trying to get the code to work for any URL with similar format
Actually this should work for arbitrary URLs (provided you can somehow get the URL into that variable). The code only makes two assumptions: 1. The URL must begin with the filename (i.e. first parameter is after first "/") 2. For each parameter name a parameter value must exist. Perhaps a regex would be a better choice here, but I can't help you with that.
0

How about using a regular expression like this?

​var url = document.URL;                             // get the current URL
var matches = url.match(/.*\/a\/(\d+)\/b\/(\d+)/);  // match it with a regex
var a = matches[1];                                 // the "a" number (as string)
var b = matches[2];                                 // the "b" number (as string)

Note that the match method returns a list, the first element of which is the overall match with the remaining items being the captured elements, i.e. the two (\d+) parts of the regex pattern. That's why this snippet uses matches[1] and matches[2] while ignoring matches[0].

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.