Pergunta

I'm building a JS library which has a requirement of looking at form[action] and a[href] values and resolving them into absolute URLs.

For example, I'm on http://a/b/c/d;p?q and encounter an href value of "../g" (assume there's no <base> element). The resulting absolute would be: http://a/b/g.

Is there a JS library that does this already? I'd have to believe so.

For more info about what's needed, the spec: http://tools.ietf.org/html/rfc3986#section-5.4

Foi útil?

Solução

It turns out that the .href attribute of a A element (not .getAttribute('href'), but .href) returns the resolved (absolute) URL.

Outras dicas

In modern browsers, the built-in URL constructor handles this:

u = (new URL("?newSearch",
             "http://a.example/with/a/long/path.file?search#fragment")).href

(yields http://a.example/with/a/long/path.file?newSearch)

If you want the base to be relative to the current document, you can do that explicitly:

u = (new URL("?newSearch", document.location)).href

The URL object also gives you access to all of the URL components (protocol, host, path, search, hash, etc.).

Nice pure JS solution that works without DOM: https://gist.github.com/1088850 (works everywhere but especially useful for server side JS).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top