I was wondering if there is a way to parse a URL in JavaScript so that you could get a piece of the URL you need? For example, the two urls below, for the first one, if I wanted to get the number at the end, what could I use? And would it be the same if I used the second URL to store 21 in a variable? Thanks.
2 Answers
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
Comments
PHPJS gives you a translation of php parse_url function which does what you want:
parse_url("http://domain.com/test/?=23");
Object {query: "=23", path: "/test/", host: "domain.com", scheme: "http"}
parse_url("http://domain.com/test/21");
Object {path: "/test/21", host: "domain.com", scheme: "http"}
num=(ua=url.split("/"))[ua.length-1]