tags:

views:

172

answers:

4

how to get base url in js file with javascript?

A: 

By "base url in js file" I assume you are after the domain:

var domain = document.domain;

If you want the base url specified in in the html document, then see David's answer

Richard
A: 

document.write(document.URL)

graphicdivine
this will give the full url, not the base url
Richard
Apologies. Try (http://www.w3schools.com/jsref/prop_base_href.asp).
graphicdivine
That assumes that a base element exists in the page (and w3schools should be avoided for the usual reasons)
David Dorward
A: 

Start with:

var base = document.getElementsByTagName('base');

… and loop backwards over them until you find one with an href attribute or get to the end.

If there is one, resolve that URL.

Otherwise, get location.href and apply a regular expression to replace /[^/]*$/ with an empty string.

David Dorward
given that the question was "base url in js file" I don't think it's for sure he's talking about <base> tag in html doc. Hence assuming he meant the domain
Richard
A: 

Use the window.location object. It'll have every piece of the URL, so whatever section you're looking for you can easily get at it. https://developer.mozilla.org/En/DOM/Window.location

Bialecki