How to get the parts of a url using document.referrer? - javascript

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:
window.location.protocol
window.location.host
window.location.pathname
but I can't figure out how to do it with document.referrer. Anyone got any ideas?

You can create an a element with the referrer as its url.
a elements (with hrefs) can act like location objects
var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';

There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:
var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');

If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

Related

how to get page url without decode in javascript?

How can I get page URL from window.location.href without decode in javascript?
For example we can not get exactly this URL: http://example.com/report#title=example_report&url=project_chart%2F%3Fproject_id%3D77.
When we use window.location.href in javascript , we will get this URL:
http://example.com/report#title=example_report&url=project_chart/?project_id=77.
But I want to get exactly the same real URL.
Any solution?
Edited
as #Eugenio told, $(document)[0].URL works fine , but Is it safe?!
Try to use encodeURI.
As for example;
var url = window.location.href;
var originalUrl = encodeURI(url);
This function(encodeURI) encodes special characters,
except: , / ? : # & = + $ #
You can use encodeURIComponent() to encode these characters.
You can use encodeURIComponent, but you have to get the part of a string you want to encode.
encodeURIComponent(window.location.href.split('&url=')[1])
Or you can use RegExp to be more precise.
Just to make a clear and concise answer I will sum up all the comments.
For your problem the best solution is to use document[x].url where x is the index of the URL part that you want to use.
The main difference for your problem between window.location.href and document.url is that the last one gives you the URL in a string format, whilest the other return the URL already parsed.
Using either one is completely normal and safe and is widely adopted in all modern browsers.
var url1 = document.URL;
var url2 = window.location.href;
document.getElementById("documentUrl").append (url1);
document.getElementById("windowLocationUrl").append (url2);
<div id="documentUrl">document.url: </div>
<div id="windowLocationUrl">window.location.href: </div>
There is no difference in this particular snippet example because there are no parameters attached to the URL. Anyway, hope this helped. Cheers!
as #Eugenio told,
i use below code and it works fine:
var url = $(document)[0].URL;

JS split OR Logical Operator

User inputs a web address that I want to get only the tail from, as I do know what site he inputs.
So first I want to remove the "main" URL and get what ever is at the end, so my action is:
Original link: http://example.com/something
var n=e.split("http://example.com/");e=n[1];
And I will get "something"
The problem is that site can also be secured, thus having https not http. Therefore the split wont work.
How do I define a split function, that would work like this:
split("http://example.com/ || https://example.com/")
I do not want to split by looking at "//" or anything of that sort, I want an exact address.
If you like it clear and want to avoid regular expressions, try this:
var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
If you wish to know the host you can do so by using this code instead in JavaScript:
window.location.host
Source Get The Current Domain Name With Javascript (Not the path, etc.)
You can also use window.location.path to get the URL that was requested, combining those you get:
window.location.host + window.location.pathname
For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.
var s = "http://example.com/something";
function split (url) {
var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
var a = r.exec(url)
return [a[1], a[2], a[3]];
}

Getting the #id from current URL

I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript.
For example:
http://my-page.com/index.html#contact-us
Would return contact-us.
I could split the URI at the eventual # and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.
Use location.hash:
location.hash.slice(1);
It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:
$('a').attr('href', url)[0].hash;
location.hash.replace(/^#/, "")
If you work with a variable:
var url = "http://my-page.com/index.html#contact-us";
var hash = url.substring(url.indexOf("#") + 1);

What's an easy way to get the url in the current window minus the domain name?

My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:
If the current url is: "http://stackoverflow.com/questions/ask"
What's a good way to to just get: "/questions/ask" ?
Basically I want a string that matches the Url without the domain or the "http://"
alert(window.location.pathname);
Here's some documentation for you for window.location.
ADDITIONAL ANSWER:
window.location.pathname itself is just not enough because it doesn't include the query part, and also URN if exists:
Sample URI = "http://some.domain/path-value?query=string#testURN"
window.location.pathname result = "/path-value"
window.location.search result = "?query=string"
pathname + search result = "/path-value?query=string"
If you want to get all the values just except the domain name, you can use the following code:
window.location.href.replace(window.location.origin, "")
Or as #Maickel suggested, with a simpler syntax:
window.location.href.substring(window.location.origin.length);
This gets the following URL parts correctly:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
Use window.location.pathname.

Javascript & HTML Getting the Current URL

Can anyone help me. I don't use Client-side Javascript often with HTML.
I would like to grab the current url (but only a specific directory) and place the results between a link.
So if the url is /fare/pass/index.html
I want the HTML to be pass
This is a quick and dirty way to do that:
//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');
//have firebug? try a console.log(loc_array);
//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]
url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"
There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.
Then, you can dynamically append the HTML to your page.
This may get you started:
var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");

Categories