2017-05-07 69 views
-1

需要幫助的得到一個URL的特定部分和動態獲取URL的特定部分,並更換

替換它,例如:

https://m.facebook.com/logout.php?h=BfcGpI0GW8PKKFtX & T = 1494184226 & BUTTON_NAME =註銷& button_location =設置。

對於此示例,我需要替換BfcGpI0GW8PKKFtX並在該點之前和之後加載URL。有沒有辦法做到這一點?具體而言,將最終看起來像這樣:

https://m.facebook.com/logout.php?h=+ replacemen + & T = 1494184226 & BUTTON_NAME =註銷& button_location =設置。任何幫助,將不勝感激。

+2

'BfcGpI0GW8PKKFtX'是否總是h的值,並且這是在Java還是Javascript中,您已經標記了Android和Javascript? –

+0

是你在尋找android原生或JavaScript更改標籤根據 – Pavan

回答

0

您還可以使用正則表達式: 「?」

var regex = /.+(\?h=|&h=)([^&]+).+/g; 
 
var url = 'https://m.facebook.com/logout.php?h=BfcGpI0GW8PKKFtX&t=1494184226&button_name=logout&button_location=settings'; 
 

 
var m, newUrl; 
 

 
while ((m = regex.exec(url)) !== null) { 
 
    // This is necessary to avoid infinite loops with zero-width matches 
 
    if (m.index === regex.lastIndex) { 
 
     ++regex.lastIndex; 
 
    } 
 
    newUrl = url.replace(m[2], 'REPLACEMENT'); 
 
    // m[2] because the first match is the whole url and 
 
    // the second one is "?h=" (or "&h="). 
 
    // the third one (index 2) is the one you want to replace. 
 
    document.getElementById("output").innerHTML = newUrl; 
 
}
<span id="output"></span>

唯一的一點是,在 「H」 參數需要是第一位的,在後。
編輯:我調整了正則表達式,以便「h」參數可以在url中的任何地方。

0

如果你想更換部分並不總是相同的,它始終是關鍵^h你可以試試:

var str = "https://m.facebook.com/logout.php?h=BfcGpI0GW8PKKFtX&t=1494184226&button_name=logout&button_location=settings"; 
 

 
var result = str.replace(str.substring(str.indexOf("h=")+2, str.indexOf("&", str.indexOf("h=")+2)), "REPLACEMENT"); 
 

 
console.log(result);

謹防可能出現的任何異常。