2012-02-19 65 views
0

我試圖獲取/ blog以便放入url_pathname。獲取存儲在變量中的URL的路徑名

var link = 'http://www.example.com/blog'; 
alert(url_pathname); 

如果該鏈接是 'http://www.example.com/blog/post',url_pathname會/博客/

我嘗試沒有成功以下。

var link = 'http://www.example.com/blog'; 
var url_pathname = link[0].pathname; 
alert(url_pathname); 

回答

2

pathname屬性僅在location對象和鏈接元素可用。字符串分配給一個錨,並宣讀了解析鏈接的值,如下所示:

var link = 'http://www.example.com/blog'; 
var a = document.createElement('a'); // Create a dummy <a> element 
a.href = link;      // Assign link, let the browser parse it 
var url_pathname = a.pathname; 
alert(url_pathname); 


你的失敗方法的說明:

  • link是一個字符串。
  • 當您使用link[0]時,會得到字符串的第一個字符h
  • 然後,您正試圖獲得它的pathname屬性。此屬性未在字符串中定義,因此您將收到undefined
    (加入這個解釋闡明爲什麼要使用JavaScript沒有拋出一個錯誤)
+0

謝謝你的時間和幫助。 – Gab 2012-02-19 17:04:25

0

試試這個,使其更簡潔:

//var link = 'http://www.example.com/blog'; // try this 
var link = "http://www.example.com/blog/post"; 
var i = link.indexOf('.com')​​​;//assuming ends in .com, find where it starts 
alert(link.substring(i+4));//use +4 to skip .com 

觀看演示:http://jsfiddle.net/c6MMz/