2011-08-01 36 views
0

我需要解析長的URL並設置一個變量(類別)等於路徑中的/folders/之一。jQuery解析我們的URL路徑的一部分

例如,URL是

http://example.com/community/home/whatever.html

我需要設置變量等於該網址後/home/任何文件夾路徑來。

我已經得到這個來警告我/ /社區/之後發生了什麼,但然後url轉向NaN和鏈接不起作用。我認爲我沒有走上正軌。

if ($(this.href*='http://example.com/community/')){ 

    var category = url.split("community/"); 

    alert(category[category.length - 1]); 

} 

想法?

TIA。

+0

對不起,我需要設置變量等於任何文件夾路徑後/來社區/在該網址。 – ben

+2

我沒有那個'this.href * ='的東西。這是什麼意思? – Malvolio

+0

jquery選擇器如果此href屬性包含http://example.com/community/ – ben

回答

2

您可以在後「/社區/」取一切用正則表達式:

var url = "http://www.example.com/community/whatever"; 
var category = ""; 
var matches = url.match(/\/community\/(.*)$/); 
if (matches) { 
    category = matches[1]; // "whatever" 
} 

工作示例這裏:http://jsfiddle.net/jfriend00/BL4jm/

如果你想只得到社會和任何之後的下一個路徑段該段後,那麼你可以使用這個:

var url = "http://www.example.com/community/whatever/more"; 
var category = ""; 
var matches = url.match(/\/community\/([^\/]+)/); 
if (matches) { 
    category = matches[1]; // "whatever" 
} else { 
    // no match for the category 
} 
這一個在這裏的

Workikng例如:http://jsfiddle.net/jfriend00/vrvbT/

+0

有用,但如果我想要返回任何內容,而不是/ asdf:http:/ /jsfiddle.net/BL4jm/2/ - 本2分鐘前編輯 – ben

+0

@ben - 我更新了我的答案,第二個選項只得到「無論」部分。 – jfriend00

+0

如果href中的字符串與該模式相匹配,但這並不能幫助我做到這一點,但通過設置category =「不匹配」,然後覆蓋它,如果它匹配,我會得到一些工作。謝了哥們! – ben

0

當你做this.href*=你在做乘法,這就是爲什麼你得到一個非數字。它將this.href乘以字符串並將其分配給href

如果你的意思是測試URL是否以該字符串開始,你可以像這樣做,不需要jQuery的:

var start = 'http://example.com/community/'; 
if (url.substring(0, start.length) === start)){ 
    var category = url.split("community/"); 
    var lastPart = category[category.length - 1]; 
    return lastPart.split("/")[0]; 
} 
+0

@ben:只需再次按「/」分隔並返回第一個結果。看到我的答案。 –