1

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.

http://domain.com/test/?=23

http://domain.com/test/21

2

2 Answers 2

5
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"

URI Parsing with Javascript

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

Comments

0

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"}

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.