How to get url from url
How to get url from url
Get URL and URL Parts in JavaScript
JavaScript can access the current URL in parts. For this URL:
So to get the full URL path in JavaScript:
A bit of a more modern way of working with URLs is the URL() global method.
If you need to break up up the pathname, for example, a URL like https://css-tricks.com/blah/blah/blah/index.html, you can split the string on “/” characters
Then access the different parts by the parts of the array, like
To put that pathname back together, you can stitch together the array and put the “/”‘s back in:
Probably the quickest way to take a peak at what you have is to put window.location in the DevTools console and see:
Comments
Really cool! Thanks!
Is there any way to extract the urls in search engine when user enters a key word in search engine by using java script….
if yes plz mail me or send me a message to 9492936947
I want to pull only “next-section”
It’s very easy by native JavaScript.
For the sake of completeness, you can also do it via document.location:
Ugh, I meant window.location
Even though both work, window.location is the safer way…
Just to mention that there was a small error:
var newURL = window.location.protocol + «//» + window.location.host + «/» + window.location.pathname;
Should have been:
var newURL = window.location.protocol + «://» + window.location.host + «/» + window.location.pathname;
Thanks Ben, fixed that.
is it possible context path…? i hope its not in browser script
Eg: http://www.kalidass.com/core
core is my context path.
It ll be change in feature
I am getting two colons while using
working fine with
@Chris, you are still missing the colon before the forward slashes in your code: «://»
I will some day become like you guy, who knows maybe even bettter.
I have a problem in webtrends reporting where the URL of the page isn’t showing up.
The URL below is a pop-up box containing a form, but the current tracking is only capturing up to the ‘?’ and so in the reporting the page name is being displayed as ‘/’ – which of course, is not correct.
Is there a way to extract the parameters at the end of this URL?
split with “?” and pick the last item.
How DOES the computer know location.pathname? Can it be a filename.location.pathname instead of window.location.pathname? It is strictly for commercial purposes.
I fix the “:” error
ie and firefox not send protocol in the same way
var fullUrl = window.location.pathname + window.location.search;
alert(fullUrl);
get url with parameters
Thanks – what I needed
How to grab the page URL when submitting enquiry form
I’m a newbie who’s stuck trying implement something like this form a web form
Can someone please provide an example of how this could be done?
this is not working very well if you send a querystring like “?test=abc/def” to the splitting function. How to avoid that?
use ‘document.URL’ for getting the full path of the current web page.
Looks like you’re missing the query/search parameters and the hash. This will get you those. 🙂
var newURL = window.location.protocol + “://” + window.location.host + “/” + window.location.pathname + window.location.search + window.location.hash;
Thanks for the post, found the info I was looking for.
I’m an uber-newbie. Would this js be useful for capturing the URL a user typed in and then sending them to an appropriate style sheet based on that URL?
Thanks – any comments/direction would be awesome..
You certainly could do that! But, it may be easier to keep 1 stylesheet and just append the class name to the body. You can google proper syntax here as I am a little short of time, but…
This would add “alternativeTheme” to the body of the document, and you would have a section in your css dedicated to it. For example:
Now, Im SURE there are all sorts of other ways to do this that are better or whatever. I’m sure somebody will post more about it. But this should get your wheels spinning as to what type of options are out there with a little bit of CSS and JS.
(This type of alternate theme could be done in a separate stylesheet. Using Sass would make it easier using nesting. If you aren’t familiar with Sass, check out the website at http://sass-lang.com/guide.
to access array from right to left:
Um, this is AWESOME.. thanks Chris.
I think you had it right the first time…
When I use your FULL URL code, I get:
http:://staging.site.com//Registration.aspx
Double : and double /
Is it a browser thing (using Chrome)?
Keep it simple stupid, lol.
Essentially what I’m trying to do is a video setup, where my url would be
and I want to just grab mp4:Video2.mp4 as a variable to use in javascript.
This URL will always be the same (besides after the = symbol) so would my code end up being something like this?
I think that most browsers return window.location.pathname with a slash in front as that is what they are supposed to do by W3C spec.
It would be best to update the “var newURL” example to check for existing slash rather than adding it in right away.
you can just use “location” ex.
var newURL = location
Thanks for the Information 😀
Hello, I need to do something very similiar. If anyone could help please.
I need a script that will extract the subdomain and add it to a new domain name to create a url that will open in a new window when clicked on.
Hope Sandra will find a solution with this.
i want to get #home and #group-text and rest of the div ids in my url in php
how it will be possible?
Hai there, for Mannan, may be you can try use :
it will return group-text..
btw, good article.. 😀
Hey pal, thank you for your posting. I need it for my JS project.
Best regards,
Anton
I guess there is still an error ( well, actually i get one using Safari / Firefox / Chrome on the mac platform):
The long-hand version should be:
or even (if I am right in the order) :
For the short-hand versions:
After testing, they seems to work cross-browsers (..)
>Btw I was desperate to find a solution to my problem (getting a [object object] instead of an URL ;p ), and I think now I can dig it deeper & debug it out (at least)
So thanks again Chris, and all the others for the info(s)
This much helpful for me. Thanks
Really useful quick reference Chris, thanks!
Would it be worth adding window.location.search and window.location.port in there too :)?
var newURL = window.location.protocol + “://” + window.location.host + “/” + window.location.pathname + “?” + window.location.search + window.location.hash;
This is the full URL, it handles php events (something.php?blah=blah) and also breaks(Hashes) (like YouTube uses to detect your location in a video) Youtube.com/#videolocation=35 (Thats an example, I don’t think that’s how they actually do it off the top of my head but I do know they use pound signs haha)
Some comments above could be added to! I completely forgot about window.location.port! Nice!
var newurl = window.location.protocol.replace(/\:/g,») + «://» + window.location.host + window.location.pathname.replace(/html/g,’php’);
sorry, mixed syntax, better like this
var newurl = window.location.protocol.replace(/\:/g,») + ‘://’ + window.location.host + window.location.pathname.replace(/html/g,’php’);
You forgot to the comparison term in the for loop…
Thanks for your post anyway ^^
Thanks for this post, as it was very helpful. I have a question in regards to parsing out everything after the “/” in the domain. Example if I have this domain http://www.google.com/patents/US20120211565. Is there a way to parse out the US20120211565 using a similar script.
Thanks for you assistance in advanced
var pathArray = window.location.pathname.split( ‘/’ );
//[«», «patents», «US20120211565»]
Using the pop method for your array would get the end if you don’t want to have to specify the index and you know it is the everything after the last ‘/’ that you want to get.
Notice on pages like this one, it ends in a ‘/’ so there is nothing after the last ‘/’
Maybe you have a url already stored in a variabled called myURL. Then you could do something like
Thank you Milo! I have an additional question hopefully you can assist. Essentially what I’m doing is this: I have about 700+ QR codes… each code has a link to a specific Patent (the google patents url provided above). I’m writing a program that when the QR code is scanned you will be directed to the patent in the same page you scanned from using an iframe (so you can continuously scan without exiting that page). The issue is Google doesn’t allow any of their pages to be embedded iframes. The solution, I’ve downloaded all the patent PDFs and renamed each to match the associated QR patent URL. When scanned, I want to take the URL and parse out the patent # and replace it with the PDF. (Hope that makes sense)
Question: Because I will be pulling multiple patent #’s, does the code you provided above still apply? Or will this code need to be tweaked.
Thanks for your assistance!
yes you can access iframes from parent document or parent document from within an iframe. look at window object or google acessing frames or parent doc from inside frame. then just do something like window.location.href = lastChunk + ‘.pdf’ or whatever path the pdfs live in
Thanks again… I was able to figure it out. This is what I did:
Again… I appreciate your assistance… helped me find a solution!
Hey Chris Coyier, Ben Chapman is wrong, or browsers have changed since then. There shouldn’t be an added colon.
Yep, just tested in Chrome Version 25.0.1364.172 m, Firefox Version 19.0.2 and Internet Explorer Version 10.0.9200.16521 and from the consoles of all three, window.location.protocol contains “http:” with the colon. I would be surprised to learn that had changed in recent years. http://stackoverflow.com/questions/4723213/detect-http-or-https-then-force-https-in-javascript is from 2011-01-18 and appears it contained a colon then.
Alrighty, putting back to original.
Is there a way to use that code to grab part of a Dynamic URL string and insert into a tracking code so I can track where leads and conversions came from?
It would need to go in the html code here where the value= would be what is dynamic.
And the URL string would be http://mywebsite.com/?c1=%5Bcsid%5D and the [csid] would be the variable that changes depending on where the traffic came from
and the http://anywebsite.com is what would be needed to be inserted into the value= part
Any help would be appreciated.
Just noticed when I inserted the code, it disappeared from my comment. the html code it would have to be inserted into would look like this “input type=”hidden” name=”TrackerName” value=”test/” ”
Let me see if this gets through
This function should be help specially when we use a local server:
return baseLocalUrl + «/»;
>
else <
// Root Url for domain name
return baseURL + «/»;
>
I use the following function to get the url parameters in an array form:
Get the full URI from the href property of a link
I would like to have a confirmation on some point.
My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. Example:
I need to get http://domain.name/test.htm from the 3 situations above (or any other identical string).
After some tests, it appears that my_a_dom_node.href always return the full-qualified URI, including the http://domaine.name, which should be okay for what I want.
The question is: can I rely on this?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
YES, you can rely!
Once when people was using simple javascript (no jQuery) many asked the opposite of what you are asking, they wanted to get the real url as written in the href attribute and not the full one, in such case they used to simply do:
Then it came jQuery that helped people not to waste their time in finding out they would need such code and jQuery always returns the real url as written in the href attribute.
It’s funny that now someone is asking how to get the full url because jQuery returns the one written in the href attribute.
I know it’s an old question, but this being actually the first entry that popped up, I believe it’s good to add an extra solution. Ever since jQuery introduced the «prop» function, getting the full URL is as simple as:
I hope that still helps somebody.
Yes, you can rely on this.
Looking through the jQuery (1.4.2) source code, I see the jQuery.attr() function being used (condensed to the relevant parts):
So it´effectively calls elem.getAttribute(‘href’) which returns the actual attribute value, while the href property by design returns the canonical URL.
This basically means that jQuery finds out browser behavior on its own and adapts accordingly to provide a consistent result.
Как разобрать URL в JavaScript?
Доброго времени суток, друзья!
Представляю Вашему вниманию перевод заметки «How to Parse URL in JavaScript: hostname, pathname, query, hash» автора Dmitri Pavlutin.
Унифицированный указатель ресурса или, сокращенно, URL — это ссылка на веб-ресурс (веб-страницу, изображение, файл). URL определяет местонахождения ресурса и способ его получения — протокол (http, ftp, mailto).
Например, вот URL данной статьи:
Часто возникает необходимость получить определенные элементы URL. Это может быть название хоста (hostname, dmitripavlutin.com ) или путь (pathname, /parse-url-javascript ).
В этой статье мы поговорим о структуре и основных компонентах URL.
1. Структура URL
Изображение лучше тысячи слов. На представленном изображении Вы можете видеть основные компоненты URL:
2. Конструктор URL()
Конструктор URL() — это функция, позволяющая разбирать (парсить) компоненты URL:
Например, инициализируем URL() с абсолютным URL:
Теперь скомбинируем относительный и абсолютный URL:
Свойство href экземпляра URL() возвращает переданную URL-строку.
Здесь тип USVString означает, что JavaScript должен возвращать строку.
3. Строка запроса (query string)
Если строка запроса отсутствует, url.search возвращает пустую строку (»):
3.1. Разбор (парсинг) строки запроса
Вместо получения исходной строки запроса, мы можем получать ее параметры.
Объект URLSearchParams предоставляет множество методов для работы с параметрами строки запроса ( get(param), has(param) и т.д.).
Давайте рассмотрим пример:
url.searchParams.get(‘message’) возвращает значение параметра message строки запроса.
4. Название хоста (hostname)
Значением свойства url.hostname является название хоста URL:
5. Путь (pathname)
Свойство url.pathname содержит путь URL:
Если URL не имеет пути, url.pathname возвращает символ / :
6. Хеш (hash)
Наконец, хеш может быть получен через свойство url.hash :
Если хеш отсутствует, url.hash возвращает пустую строку (»):
7. Проверка (валидация) URL
Например, http ://example.com не валидный URL, поскольку после http имеется пробел.
Попробуем использовать этот URL:
8. Работа с URL
Такие свойства, как search, hostname, pathname, hash доступны для записи.
Например, давайте изменим название хоста существующего URL с red.com на blue.io :
Свойства origin, searchParams доступны только для чтения.
9. Заключение
Конструктор URL() является очень удобным способом разбора (парсинга) и проверки (валидации) URL в JavaScript.
new URL(relativeOrAbsolute, [, absoluteBase] в качестве первого параметра принимает абсолютный или относительный URL. Если первый параметр является относительным URL, вторым параметром должен быть абсолютный URL — основа для первого аргумента.
What is the correct way to pull out just the path from a URL using JavaScript?
I am using jQuery if there is anything there that can be leveraged.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
There is a property of the built-in window.location object that will provide that for the current window.
Update, use the same properties for any URL:
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
JSFiddle example
There’s also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
Will give you an array containing all the URL parts, which you can access like a normal array.
Or an ever more elegant solution suggested by @Dylan, with only the path parts:
If this is the current url use window.location.pathname otherwise use this regular expression:
There is a useful Web API method called URL
If you have an abstract URL string (not from the current window.location ), you can use this trick:
In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse
According to the documentation, it extracts the following parts:
The returned url instance contains the following properties:
How to get only path from full url string
Can I only get the path /MyRouterName (for all cases) from the full url?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can use the activated route component’s snapshot to get this url.
Link to original SO answer by Jose G Varanam How to get current route
The answer user5049376 has given didn’t work for me. the url property was undefined.
instead of that I used the firstChild property.
This works for me.
then pass it to the constructor :
I have tried to use the other responses and they all end up with undefined.
I subscribe to the router changes so when NavitionStartEvent happens a new URL_PATH is found.
Isn’t this simple and effective?
For me, this is the cleanest solution I managed to do. I hope it helps
If you don’t need to support IE you can use the URL class to do reverse-engineer the url components from the string:
Considering your example, the code above would yield only the «/MyRouterName» part of «/MyRouterName?type=abc».