11

In JavaScript, is there any class equivalent for

  • NSURL class in iOS SDK or
  • URL class in Java?

With such class, I want to:

  • normalize URL,
  • compose a URL from scheme, host, path components, etc..., and
  • decompose a URL into its elements.
2

2 Answers 2

13

James Padolsey had tackled this problem.

In a nutshell, you can create an anchor element using document.createElement(), and several of its native properties are then easily accessible, such as protocol, port, and hostname.

For more information: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

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

3 Comments

That is beautiful! I'd vote twice if it's possible. Using the <a> tag to parse url via href is brilliant!
Yup, that was my reaction too, when I read that blog entry. It was literally under our noses the entire time.
BEAUTIFULL. And I never use all caps.
6

Yes! There is now a standard, broadly compatible, URL class for Javascript.

The constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative URL

const url = new URL(window.location.href);
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"

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.