2012-03-13 17 views
8

我有一個網址:如何從一個字符串切換到使用Javascript結束的子字符串?

http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe 

我想用JavaScript來獲得最後的衝刺後,地址:

dashboard.php?page_id=projeto_lista&lista_tipo=equipe 
+0

嗨Erick,你分享的鏈接是在你的本地機器上,因此不可見。如果你用一個簡單的代碼片段來重述你的問題,那麼我可以嘗試回答 – Rowan 2012-03-13 20:15:18

+0

你的子串是否總是啓動'/ dashboard ...'?編輯:@Rowan,鏈接只是他試圖從中刪除子串的字符串的一個例子。我希望。 – 2012-03-13 20:15:26

+0

哈哈,哎呀。失敗:)收聽@Elliot - 讓我感到困惑,因爲它顯示爲一個鏈接,自然反應是點擊 – Rowan 2012-03-13 20:16:46

回答

16

您可以使用indexOfsubstr得到你想要的子字符串:

//using a string variable set to the URL you want to pull info from 
//this could be set to `window.location.href` instead to get the current URL 
var strIn = 'http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe', 

    //get the index of the start of the part of the URL we want to keep 
    index = strIn.indexOf('/dashboard.php'), 

    //then get everything after the found index 
    strOut = strIn.substr(index); 

strOut變量現在包含/dashboard.php之後的所有內容(包括該字符串)。

這裏是一個演示:http://jsfiddle.net/DupwQ/

文檔 -

+1

完美!謝謝! – 2012-03-13 20:20:25

4

本地JavaScript字符串的方法substr[MDN]可以完成你所需要的。只需提供起始索引並省略長度參數,並且一直抓到最後。

現在,如何獲取起始索引?你沒有給出任何標準,所以我不能真正幫助。

+0

我覺得不那麼容易。 substr找不到一組特定的字符。 – 2012-03-13 20:18:51

+0

是的。爲此,您需要找到起始索引。 – FishBasketGordo 2012-03-13 20:19:47

4

如果開始總是 「HTTP://本地主機/ 40ATV」 你可以這樣做:

var a = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe"; 
var cut = a.substr(22); 
+1

這可能有助於解釋某些事情有時可以發揮作用,而不僅僅是用功利的答案回答問題。 substr/substring和indexOf都是可以/應該被覆蓋的重要操作。 – Tracker1 2012-03-13 21:18:40

+0

感謝您的輸入。我在這裏是新的,所以請裸露在我:) – fruitcup 2012-03-14 00:30:59

+0

沒有問題..只是提供更多建設性的答案的意見。 :) – Tracker1 2012-03-14 17:50:33

1

無需jQuery的,老式的JavaScript只會做的工作精細。

var myString = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe"; 
var mySplitResult = myString.split("\/"); 
document.write(mySplitResult[mySplitResult.length - 1]);​ 

,如果你想領先/

document.write("/" + mySplitResult[mySplitResult.length - 1]);​ 
0

所有SPLIT URL首先:

var str = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe"; 
var arr_split = str.split("/"); 

找到最後一個數組:

var num = arr_split.length-1; 

你得到廣告最後的衝刺後打扮:

alert(arr_split[num]); 
1

這可能是新的,但substring方法返回的一切從指定索引到字符串的結尾。

var string = "This is a test"; 

console.log(string.substring(5)); 
// returns "is a test" 
相關問題