I want to show the domain that user came from to my page with document.referrer
. But I dont want to show all name of this site for example: www.mysite.pl/page2314 but only the domain - www.mysite.pl
How to do that?
I want to show the domain that user came from to my page with document.referrer
. But I dont want to show all name of this site for example: www.mysite.pl/page2314 but only the domain - www.mysite.pl
How to do that?
You can among other things use a regular expression like this:
var referrer = document.referrer
var doman = referrer.match(/:\/\/([^/]+)\//)[1]
This will match anything in an url after ://
up to (but not including) the following /
.
If document.referrer
is http://stackoverflow.com/questions
, the matched domain will be stackoverflow.com
.
What about a regex which only matchs the first part ? like
Edited: thx @David
document.referrer.match(/((ht{1}(tp|tps):\/\/)[\w\d\S]+?)\//g)[0] //"http://stackoverflow.com/"
Of course you can use any suitable regex
var ref = document.referrer;
ref = ref.substring(ref.indexOf("://") + 3)
ref = ref.split("/")[0];
Now ref only contains the domain. A different approach would be with regex.