我有一個像這樣的網址http://mywebsite.com/folder1/folder2/indexJavaScript網址解析
如何解析上述url並獲取所有值分開? 我所要的輸出是這樣的:
http, mywebsite.com, folder1, folder2, index
我有一個像這樣的網址http://mywebsite.com/folder1/folder2/indexJavaScript網址解析
如何解析上述url並獲取所有值分開? 我所要的輸出是這樣的:
http, mywebsite.com, folder1, folder2, index
如果您的網址是一個變量中,你可以使用split()方法執行以下操作:
var url = 'http://mywebsite.com/folder1/folder2/index';
var path = url.split('/');
// path[0] === 'http:';
// path[2] === 'mywebsite.com';
// path[3] === 'folder1';
// path[4] === 'folder2';
// path[5] === 'index';
如果你想解析文檔的當前URL,你可以在window.location
工作:
var path = window.location.pathname.split('/');
// window.location.protocol === 'http:'
// window.location.host === 'mywebsite.com'
// path[1] === 'folder1';
// path[2] === 'folder2';
// path[3] === 'index';
代碼
var s = "http://mywebsite.com/folder1/folder2/index";
var list = s.split("/")
console.log(list);
輸出
["http:", "", "mywebsite.com", "folder1", "folder2", "index"]
var reader = document.createElement('a');
reader.href = "http://test.example.com:80/pathname/?query=param#hashtag";
然後你可以用以下屬性:
reader.protocol
reader.hostname
reader.port
reader.pathname
reader.search
reader.hash
reader.host;
感謝....它的作品... 。 – 2010-05-05 05:47:35