jquery получить текущий url

Рассмотрим как получить URL текущей страницы на javascript вместе с get параметрами и доменным именем сайта. Полная информация об адресе содержится в объекте «document.location». Доступ к отдельным элементам можно получить с помощью обращения к свойствам объекта.

Свойство Значение
document.location.href http://realadmin.ru/saytostroy/?page=4#top
document.location.protocol http:
document.location.host realadmin.ru
document.location.pathname /saytostroy/
document.location.search ?page=4
document.location.hash #top

Получаем GET параметр

Теперь получим из адресной строки значение конкретного GET параметра. Для этого присвоим их переменной и выберем нужное значение регулярным выражением. Для примера возьмём URL и извлечем значение параметра «limit»:

Если «limit» не существует, то переменная «GetValue» будет содержать пустую строку.

Объект Location связан с адресной строкой браузера, в его свойствах содержатся все компоненты URL доступные для чтения и записи.

Доступ к Location обычно осуществляется через объекты Document.location или Window.location . Если скрипт запускается из iframe (в одном домене), доступ к родительскому окну доступен через window.parent.location .

Рассмотрим какие будут значения при следующим URL:

Location.href

Вернет полный URL страницы.

Объекту location можно присвоить новый URL, браузер сразу перейдет на новую страницу.

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

31 Answers 31

To get the path, you can use:

In pure jQuery style:

The location object also has other properties, like host, hash, protocol, and pathname.

This will work only if you have jQuery. For example:

If you need the hash parameters present in the URL, window.location.href may be a better choice.

You’ll want to use JavaScript’s built-in window.location object.

Just add this function in JavaScript, and it will return the absolute path of the current path.

I hope it works for you.

window.location is an object in javascript. it returns following data

in jquery you can use

This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location or document.location . However, different flavors of Internet Explorer (6,7) don’t support these methods in the same way, ( window.location.href ? window.location.replace() not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.

So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.

Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.

For the host name only, use:

This will also work:

java-script provides many methods to retrieve current URL which is displayed in browser’s address bar.

Function:

  • protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)

EX: With default port numbers

  • (//) « Host is the name given to an end-point(machine on which resource lives) on the Internet. www.stackoverflow.com — DNS IP Address of an Application (OR) localhost:8080 — localhost

Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy the Root name of an stackoverlfow.com is com.

Local system you have to maintain domain’s which are not PUBLIC in Host Files. localhost.yash.com « localhsot — subdomain( web-server ), yash.com — maindomain( Proxy-Server ). myLocalApplication.com 172.89.23.777

  • (/) « The path gives info about the specific resource within the host that the Web client wants to access
  • (?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
  • (#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.

If parameter has an Epoch ?date=1467708674 then use.

Authentication url with username:password, If usernaem/password contains @ symbol
like:

then You need to URL encode the @ as %40 . Refer.

Оцените статью