2012-01-12 155 views
1

我在這裏的第一篇文章,但我已經通過潛伏=)瞭解了很多這一次,我找不到問題的解決方案,雖然它看起來像是很容易實現的東西。截斷與jQuery的鏈接

我有一個使用Feed2JS生成的blogpost鏈接列表。不幸的是,這個RSS源是這個鏈接添加了我不想要的鏈接。我無法更改Feed,因爲它是在RapidWeaver中自動生成的。

是否有可能從jQuery的URL中的哈希中刪除所有內容?例如:改變

http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php#unique-entry-id-31

http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php

我是相當新的jQuery的,而且還有很多東西需要學習,所以請保持你的答案簡單。

的Jeroen

回答

0

我喜歡做這種方式:

var a = document.createElement("a"); 
a.href = "http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php#unique-entry-id-31"; 
alert(a.protocol + "://" + a.host + a.pathname + a.search); 

http://jsfiddle.net/karim79/7pMbk/1

+0

削減了用戶名和密碼 – 2012-01-12 10:33:09

0

當然,你可以做這樣的事情:

var str = 'http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php#unique-entry-id-31'; 
var substr = str.split('#'); 
// substr[0] contains "http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php" 
// substr[1] contains "unique-entry-id-31" 

注意,這是從JavaScript API。

+0

謝謝你們, 非常感激! – Jeroen 2012-01-12 11:13:15

0

你不需要使用jQuery爲:

function truncate(href) { 
    var a = document.createElement('a'); 
    a.setAttribute('href', href); 

    a.hash = ''; 
    return a.href; 
} 
1

,如果你只是想截斷的網址,你可以做到這一點作爲

var url = "http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php#unique-entry-id-31"; 
var index = url.indexOf('#') != -1 ? url.indexOf('#') : url.length 
alert(url.substring(0,index)); 

OUTPUT:

http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php 

示例:http://jsfiddle.net/2dXXx/

+0

不適用於沒有散列的網址 – 2012-01-12 10:32:33

+0

是啊我的壞..更新了代碼.. – 2012-01-12 11:06:23

0

需要jQuery的不依賴,你可以使用正則表達式,如本jsFiddle

var url = "http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.php#unique-entry-id-31" 
console.log("base url >> " + url)  
var matcher = /(.*)#.*/.exec(url) 
var truncated = matcher[1] 
console.log("truncated url >> " + truncated)  
0
var url = "http://www.example.com/blog/files/398e042ea42b7ee9d1678b3c53132fc3-31.phpunique-entry-id-31"; 

alert(url.substring(0,url.indexOf('#'))); // will give you empty string if you dont have # in the url. 

所以表現出來,你可以使用

alert(url.split('#')[0]);