我有一個網址:如何從一個字符串切換到使用Javascript結束的子字符串?
http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe
我想用JavaScript來獲得最後的衝刺後,地址:
dashboard.php?page_id=projeto_lista&lista_tipo=equipe
我有一個網址:如何從一個字符串切換到使用Javascript結束的子字符串?
http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe
我想用JavaScript來獲得最後的衝刺後,地址:
dashboard.php?page_id=projeto_lista&lista_tipo=equipe
您可以使用indexOf
和substr
得到你想要的子字符串:
//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/
文檔 -
完美!謝謝! – 2012-03-13 20:20:25
本地JavaScript字符串的方法substr
[MDN]可以完成你所需要的。只需提供起始索引並省略長度參數,並且一直抓到最後。
現在,如何獲取起始索引?你沒有給出任何標準,所以我不能真正幫助。
我覺得不那麼容易。 substr找不到一組特定的字符。 – 2012-03-13 20:18:51
是的。爲此,您需要找到起始索引。 – FishBasketGordo 2012-03-13 20:19:47
如果開始總是 「HTTP://本地主機/ 40ATV」 你可以這樣做:
var a = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe";
var cut = a.substr(22);
無需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]);
所有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]);
這可能是新的,但substring方法返回的一切從指定索引到字符串的結尾。
var string = "This is a test";
console.log(string.substring(5));
// returns "is a test"
嗨Erick,你分享的鏈接是在你的本地機器上,因此不可見。如果你用一個簡單的代碼片段來重述你的問題,那麼我可以嘗試回答 – Rowan 2012-03-13 20:15:18
你的子串是否總是啓動'/ dashboard ...'?編輯:@Rowan,鏈接只是他試圖從中刪除子串的字符串的一個例子。我希望。 – 2012-03-13 20:15:26
哈哈,哎呀。失敗:)收聽@Elliot - 讓我感到困惑,因爲它顯示爲一個鏈接,自然反應是點擊 – Rowan 2012-03-13 20:16:46