2012-04-25 323 views

回答

12
var url = "http://www.ronniej.com/linkdes.com/?adv=267&loc=897" 
var referrer = url.match(/:\/\/(.[^/]+)/)[1]; 

http://jsfiddle.net/hyjcD/

if (document.referrer) { 
    url = document.referrer; 
    ref = url.match(/:\/\/(.[^/]+)/)[1]; 
} 
+0

@Reminson感謝這..它的作品,但我有一個問題..我已經把代碼放在我的域名使用.js文件,基本上它被加載到所有頁面上。唯一的問題是這個。每當我直接訪問一個頁面(沒有引用URL)時,我得到以下錯誤:url.match(/:\/\ /(。[^ /] +)/)[1]; **爲空** – Stephen 2012-04-25 15:00:33

+0

我使用的是: var url = unescape(document.referrer); var ref = url.match(/:\/\ /(。[^ /] +)/)[1]; – Stephen 2012-04-25 15:04:11

+0

這是因爲'document.referrer'是'undefined',並且沒有匹配的url,你應該檢查if(document.referrer)是不是「undefined」,然後執行這段代碼。 – undefined 2012-04-25 15:05:00

4

鏈分割,切片和加入:

document.referrer.split("/").slice(0,3).join("/") 
8

您可以在內部使用的URL寫入定位元素,並從一個拿到小部分

var anchor = document.createElement("a"); 
anchor.href = "http://www.davidj.com/pages/flyer.asp"; 

console.log(anchor.protocol + "//" + anchor.host); // "http://www.davidj.com" 

要容易得多然後根據你不必關心分裂或類似的東西......這是非常合乎邏輯的...本地錨點具有相同的屬性,如window.location至少關於URL

編輯:IE 6-9添加默認端口anchor.host //「http://www.davidj.com:80

+1

IE瀏覽器出現在端口添加到'anchor.host',而不是'location.host'。如果您不需要端口,則可以使用'anchor.hostname'和'location.hostname'。 – 2012-08-23 15:43:23

+0

感謝分享 – 2012-08-23 18:34:26

0

你可以使用正則表達式:

var matchHost = /^https?:\/\/.*\//; 

var match = matchHost.exec('http://www.davidj.com/pages/flyer.asp'); 
if(match) { 
    var host = match[0]; 
    console.log(host); 
} 
0
if (document.referrer.split('/')[2] == "domain") { 
    //................ 
}