那麼我目前有一些關於操縱URL的問題。從字符串URL獲取域名和頁面名稱
從技術上講,我想要的是從頁面獲取域名和頁面名稱。
例如:
www.myWebSite.com => domain : myWebSite
http://myWebSite.com => domain : myWebSite
myWebSite.com/xxx.hmtl => domain : myWebSite page : xxx
那麼我目前有一些關於操縱URL的問題。從字符串URL獲取域名和頁面名稱
從技術上講,我想要的是從頁面獲取域名和頁面名稱。
例如:
www.myWebSite.com => domain : myWebSite
http://myWebSite.com => domain : myWebSite
myWebSite.com/xxx.hmtl => domain : myWebSite page : xxx
window.location.hostname; //Domain name
$("title").text(); //Page name
編輯:
var loc = window.location;
var filename = loc.pathname.split("/");
filename = filename[pathname.length-1];
alert("Domain: "+loc.hostname);
alert("Filename: "+filename);
使用window.location.hostname
或window.location.host
。檢查location reference。
嘗試/:\/\/(.[^/]+)/.match(url)[1]
例如:
var r = /:\/\/(.[^/]+)/;
"http://stackoverflow.com/questions/5343288/get-the-domain-and-page-name-from-a-string-url".match(r)[1]
=> stackoverflow.com
我希望這有助於:
function breakDownURL(url) {
var domain = "",
page = "";
//remove "http://"
if (url.indexOf("http://") == 0) {
url = url.substr(7);
}
//remove "www."
if (url.indexOf("www.") == 0) {
url = url.substr(4);
}
domain = url.split('/')[0].split('.')[0]
if (url.split('/').length > 1) {
page = url.split('/')[1].split('.')[0];
}
document.write("domain : " + domain +
(page == "" ? "" : " page : " + page) + page + "<br/>");
}
breakDownURL("www.myWebSite.com"); // domain : myWebSite
breakDownURL("http://myWebSite.com"); // domain : myWebSite
breakDownURL("myWebSite.com/xxx.html"); // domain : myWebSite page : xxx
var url = window.location.href; //www.myWebSite.com/myWebSite
var arr = url.split("/");
var page = arr[arr.length-1];
var domain = window.location.host;
alert(domain); //www.myWebSite.com
var n = page.includes("?"); // if www.myWebSite.com/myWebSite?parameter
if(n)
{
var page_arr = page.split("?");
var page = page_arr[0]; //myWebSite
}
alert(page); //myWebSite
。3月應該是.match – Parker 2014-01-15 05:31:59